Javascript 中 window.onload 和 document.onload 的區別是什麼?


document.onload

影像和其他外部內容載入之前觸發。document.onload 事件在 window.onload 之前觸發。

window.onload

當整個頁面載入完畢時觸發,包括影像、指令碼、CSS 等。

示例

以下示例有助於瞭解 onload 的用法。

實際演示

<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>

更新於:2020 年 6 月 15 日

1,000+ 次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.