时间:2021-07-01 10:21:17 帮助过:38人阅读
<!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的使用方法的详细内容,更多请关注Gxl网其它相关文章!