<!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>
In this case, if you put js in window.onload An error will be reported inside.
Analysis: The js placed in onload will wait for the html to be loaded before executing the function, but when loading the html, there is onclick="btn('box1')"
, this function will not be found (because the function has not been loaded at this time). To call this function, it must be loaded.
<!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>
The above is the detailed content of How to use window.onload. For more information, please follow other related articles on the PHP Chinese website!