window.onload() 方法用于在網(wǎng)頁(yè)加載完畢后立刻執(zhí)行的操作,即當(dāng) HTML 文檔加載完畢后,立刻執(zhí)行某個(gè)方法。
window.onload() 通常用于 <body> 元素,在頁(yè)面完全載入后(包括圖片、css文件等等)執(zhí)行腳本代碼。
只有一個(gè)要執(zhí)行的函數(shù)語(yǔ)法:
window.onload = funcRef;
在頁(yè)面加載完成后 funcRef 方法會(huì)被調(diào)用。
有多個(gè)要執(zhí)行的函數(shù)語(yǔ)法:
window.onload=function(){ Func1(); Func2(); Func3(); ..... }
在頁(yè)面加載完成后依次執(zhí)行 Func1、Func2、Func3。
為什么使用 window.onload()?
因?yàn)?JavaScript 中的函數(shù)方法需要在 HTML 文檔渲染完成后才可以使用,如果沒(méi)有渲染完成,此時(shí)的 DOM 樹是不完整的,這樣在調(diào)用一些 JavaScript 代碼時(shí)就可能報(bào)出”undefined”錯(cuò)誤。
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>沒(méi)有使用 window.onload() 測(cè)試</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>
嘗試一下 ?
以上實(shí)例我們要實(shí)現(xiàn)的效果是將 div 的背景顏色設(shè)置為 #F90,但是并沒(méi)有實(shí)現(xiàn)此效果,因?yàn)榇a是順序執(zhí)行的,當(dāng)執(zhí)行到 document.getElementById(“#bg”).style.backgroundColor=”#F00″ 的時(shí)候,還沒(méi)有加載到此 div 對(duì)象,所以背景顏色沒(méi)有設(shè)置成功。報(bào)錯(cuò)信息如下:

我們可以添加 window.onload 就可以正常執(zhí)行,代碼修改如下:
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>使用 window.onload() 測(cè)試</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ù),綁定的是一個(gè)匿名函數(shù),當(dāng)然也可以綁定具名函數(shù),代碼實(shí)例如下:
實(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ù),更是夢(mèng)想?。?!"); } </script> </head> <body> </body> </html>
嘗試一下 ?
有多個(gè)要執(zhí)行的函數(shù)實(shí)例:
實(shí)例
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>使用 window.onload() 執(zhí)行多個(gè)函數(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>
嘗試一下 ?