在HTML中打印文档之前执行脚本?


我们将在本文中执行的任务是在HTML中打印文档之前执行脚本。

当页面即将打印时,将使用HTML的onbeforeprint属性。在打印对话框出现之前,将显示警报消息。onbeforeprint属性与onafterprint属性一起使用。这是事件属性的一部分。

让我们深入研究以下示例,以了解如何在HTML中打印文档之前执行脚本。

示例1

在以下示例中,我们使用HTML的onbeforeprint属性。

<!DOCTYPE html>
<html>
   <body onbeforeprint="mytutorial()">
   <h1>MS DHONI</h1>
   <h2>Finishes off in his Style.</h2>
   <script>
      function mytutorial() {
         alert("Sure To Print!");
      }
   </script>
</body>
</html>

当脚本执行时,它将生成一个输出,在网页上显示脚本中使用的文本。

当用户尝试打印网页时,事件被触发并在网页上显示“确定打印”的警报。

示例2

这是另一个实现onbeforeprint属性的示例。

<!DOCTYPE html>
<html>
   <body onbeforeprint = "display()">
   <h1>TUTORIALSPOINT</h1>
   <script>
      function display() {
         alert("The document will now print.");
      }
   </script>
</body>
</html>

运行上述脚本后,输出窗口弹出并在网页上显示文本“tutorialspoint”。

如果用户尝试打印网页,事件被触发并在网页上显示警报。

更新于:2022年12月16日

225 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.