Computer >> Máy Tính >  >> Lập trình >> Javascript

Sự khác biệt giữa window.onload và document.onload trong Javascript là gì?

document.onload

Nó được kích hoạt trước khi tải hình ảnh và nội dung bên ngoài khác. tài liệu. onload sự kiện được kích hoạt trước window.onload.

window.onload

Nó được kích hoạt khi tải trang hoàn chỉnh, bao gồm hình ảnh, tập lệnh, css, v.v.

Ví dụ

Đây là một ví dụ để hiểu về tải trọng.

Bản trình diễn trực tiếp

<html>
   <head>
      <title>JavaScript Animation</title>
      <script>
         <!--
            var imgObj = null;
         
            function init() {
               imgObj = document.getElementById('myImage');
               imgObj.style.position= 'relative';
               imgObj.style.left = '0px';
            }

            function moveRight() {
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
            }
            window.onload =init;
         //-->
      </script>
   </head>

   <body>
      <form>
         <img id="myImage" src="/images/html.gif" />
         <p>Click button below to move the image to right</p>
         <input type="button" value="Click Me" onclick="moveRight();" />
      </form>
   </body>
</html>