<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> p{ width: 100px; height: 100px; background: red; margin-left: 50px; margin-top: 30px; display: none; } </style> <script type="text/javascript">// window.onload=function(){// function btn(obj){// var box=document.getElementById(obj);// box.style.display="block";// }// } function btn(obj){ var box=document.getElementById(obj); box.style.display="block"; } </script> </head> <body> <button onclick="btn('box1')" >显示第一个盒子</button> <button onclick="btn('box2')">显示第二个盒子</button> <button onclick="btn('box3')" >显示第三个盒子</button> <button onclick="btn('box4')">显示第四个盒子</button> <p id="box1">1</p> <p id="box2">2</p> <p id="box3">3</p> <p id="box4">4</p> </body></html>
這種情況下,如果把js放在window.onload裡面會報錯。
解析:放在onload中的js會等html載入完再執行函數,但是在載入html的時候,裡面有onclick="btn('box1')"
,會找不到這個函數(由於這個時候函數還沒有載入)。要呼叫這個函數,就要讓它載入完畢。
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>111</title> <style> * { margin: 0; padding: 0; list-style-type: none; } #box { width: 360px; padding-top: 360px; background:url(image/01big.jpg) no-repeat center top; margin: 100px auto; border: 1px solid blueviolet; overflow: hidden; } ul { border-top: 1px solid blueviolet; } li { float: left; } </style> <script> window.onload=function() { var box =document.getElementById("box"); function fun(id,bg) { var ID =document.getElementById(id); ID.onmouseover=function() { box.style.backgroundImage=bg; } } fun("id1","url(image/01big.jpg)"); fun("id2","url(image/02big.jpg)"); fun("id3","url(image/03big.jpg)"); fun("id4","url(image/04big.jpg)"); fun("id5","url(image/05big.jpg)"); } <script> window.onload=function(){ var box =document.getElementById("box"); function fun(id,bg){ var ID =document.getElementById(id); ID.onmouseover=function(){ box.style.backgroundImage=bg; } } fun("id1","url(image/01big.jpg)"); fun("id2","url(image/02big.jpg)"); fun("id3","url(image/03big.jpg)"); fun("id4","url(image/04big.jpg)"); fun("id5","url(image/05big.jpg)"); } </script></head><body> <p id="box"> <ul> <li id="id1"><img src="image/01.jpg" alt=""/></li> <li id="id2"><img src="image/02.jpg" alt=""/></li> <li id="id3"><img src="image/03.jpg" alt=""/></li> <li id="id4"><img src="image/04.jpg" alt=""/></li> <li id="id5"><img src="image/05.jpg" alt=""/></li> </ul> </p></body></html>
以上是window.onload的使用方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!