Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript onload

在JavaScript中,当页面完全显示时,此事件可用于启动特定功能。它还可以用来验证访问者浏览器的类型和版本。我们可以使用 onload 属性来检查页面使用的cookie。
在HTML中,加载对象时会触发onload属性。此属性的目的是在关联元素加载时执行脚本。
在HTML中, onload 属性通常与 <body>元素一起使用,以在网页内容(包括CSS文件,图像,脚本等)完全完成后执行脚本。已加载。不必仅将它与<body>标签一起使用,因为它可以与其他HTML元素一起使用。
document.onload window.onload 之间的区别是: document.onload 在加载图像之前触发和其他外部内容。它在 window.onload 之前触发。当 window.onload 在整个页面加载时触发,包括CSS文件,脚本文件,图片等。

语法

window.onload = fun()
让我们通过使用一些示例来了解此事件。

Example1

在此示例中,有一个div元素,其高度为200px,宽度为200 200px。在这里,我们使用 window.onload()进行更改加载网页后 div 元素的背景颜色,宽度和高度。
背景颜色设置为 '红色',宽度和高度分别设置为 300px
<!DOCTYPE html>
<html>
<head>
<meta charset = " utf-8">
<title> window.onload() </title>
<style type = "text/css">
#bg{
width: 200px;
height: 200px;
border: 4px solid blue;
}
</style>
<script type = "text/javascript">
window.onload = function(){
document.getElementById("bg").style.backgroundColor = "red";
document.getElementById("bg").style.width = "300px";
document.getElementById("bg").style.height = "300px";
}
</script>
</head>
<body>
<h2> This is an example of window.onload() </h2>
<div id = "bg"></div>
</body>
</html>
输出
执行代码并加载页面后,输出将为-
 JavaScript onload

Example2

在此示例中,我们通过使用DOM对象的属性和javascript的功能。我们使用JavaScript函数getElementById()来获取DOM对象,然后将该对象分配给全局变量。
<html>
   <head>
      <script type = "text/javascript">
    var img = null;
    function init(){
       img = document.getElementById('myimg');
       img.style.position = 'relative';
       img.style.left = '50px';
    }
    function moveRight(){
       img.style.left = parseInt(
       img.style.left) + 100 + 'px';
    }
    window.onload = init;
      </script>
   </head>
   <body>
      <form>
 <img id = "myimg" src = "train1.png" />
 <center>
    <p>Click the below button to move the image right</p>
 <input type = "button" value = "Click Me" onclick = "moveRight();" />
      </center>
      </form>
   </body>
</html>
输出
成功执行以上代码后,输出为-
 JavaScript onload
现在,有一个示例,其中我们将使用HTML onload 属性和JavaScript函数。

Example3

这是将HTML onload 属性与JavaScript中定义的函数结合使用的简单示例。在此示例中,只要刷新文档,就会调用 alert()函数。
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script>
   function fun() {
      alert("Hello World!!, Welcome to the lidihuo.com");
   }
</script>
</head>
<body onload = "fun()">
<h1> Example of the HTML onload attribute </h1>
<p> Try to refresh the document to see the effect. </p>
</body>
</html>
输出

Example of the HTML onload attribute

Try to refresh the document to see the effect.

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4