window.onload() 方法用于在網(wǎng)頁加載完畢后立刻執(zhí)行的操作,即當(dāng) HTML 文檔加載完畢后,立刻執(zhí)行某個方法。
window.onload() 通常用于 <body> 元素,在頁面完全載入后(包括圖片、css文件等等)執(zhí)行腳本代碼。
只有一個要執(zhí)行的函數(shù)語法:
window.onload = funcRef;
在頁面加載完成后 funcRef 方法會被調(diào)用。
有多個要執(zhí)行的函數(shù)語法:
window.onload=function(){ Func1(); Func2(); Func3(); ..... }
在頁面加載完成后依次執(zhí)行 Func1、Func2、Func3。
為什么使用 window.onload()?
因為 JavaScript 中的函數(shù)方法需要在 HTML 文檔渲染完成后才可以使用,如果沒有渲染完成,此時的 DOM 樹是不完整的,這樣在調(diào)用一些 JavaScript 代碼時就可能報出”undefined”錯誤。
實例
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>沒有使用 window.onload() 測試</title> <style type="text/css"> #bg{ width:120px; height:120px; border:4px solid blue; } </style> <script type="text/javascript"> document.getElementById("bg").style.backgroundColor="#F00"; </script> </head> <body> <div id="bg"></div> </body> </html>
嘗試一下 ?
以上實例我們要實現(xiàn)的效果是將 div 的背景顏色設(shè)置為 #F90,但是并沒有實現(xiàn)此效果,因為代碼是順序執(zhí)行的,當(dāng)執(zhí)行到 document.getElementById(“#bg”).style.backgroundColor=”#F00″ 的時候,還沒有加載到此 div 對象,所以背景顏色沒有設(shè)置成功。報錯信息如下:
我們可以添加 window.onload 就可以正常執(zhí)行,代碼修改如下:
實例
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>使用 window.onload() 測試</title> <style type="text/css"> #bg{ width:120px; height:120px; border:4px solid blue; } </style> <script type="text/javascript"> window.onload=function(){ document.getElementById("bg").style.backgroundColor="#F00"; } </script> </head> <body> <div id="bg"></div> </body> </html>
嘗試一下 ?
window.onload 事件綁定事件處理函數(shù),綁定的是一個匿名函數(shù),當(dāng)然也可以綁定具名函數(shù),代碼實例如下:
實例
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>使用 window.onload() 綁定具體函數(shù)</title> <script type="text/javascript"> // 函數(shù)名為 runoob window.onload=function runoob(){ document.write("菜鳥教程 — 學(xué)的不僅是技術(shù),更是夢想!??!"); } </script> </head> <body> </body> </html>
嘗試一下 ?
有多個要執(zhí)行的函數(shù)實例:
實例
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>使用 window.onload() 執(zhí)行多個函數(shù)</title> <style type="text/css"> #bg{ width:100px; height:100px; border:2px solid red; } </style> <script type="text/javascript"> window.onload=function(){ function runoob1(){ document.getElementById("bg").style.backgroundColor="#F00"; } function runoob2(){ document.getElementById("bg").style.width="200px"; document.getElementById("bg").style.height="200px"; } runoob1(); runoob2(); } </script> </head> <body> <div id="bg"></div> </body> </html>
嘗試一下 ?