关于window.onload的一点认识

来源:互联网 发布:淘宝只能手机号注册吗 编辑:程序博客网 时间:2024/05/21 09:50
<!DOCTYPE html>
<html>


<head>
<meta charset="utf-8" />
<title>DIV CSS遮罩层</title>
<script language="javascript" type="text/javascript">
function showdiv() {
document.getElementById("bg").style.display = "block";
document.getElementById("show").style.display = "block";
}


function hidediv() {
document.getElementById("bg").style.display = 'none';
document.getElementById("show").style.display = 'none';
}
window.onload = function() {
var clk = document.getElementById('show_hd');
clk.onclick = function() {
alert("单击 ");
}

}
</script>
<style type="text/css">
#bg {
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index: 10;
-moz-opacity: 0.7;
opacity: 0.7;
}

#show {
display: none;
position: absolute;
top: 25%;
left: 20%;
width: 53%;
height: 49%;
border: 8px solid red;
background-color: #fff;
z-index: 1002;
overflow: auto;
}

#btnclose {
background: green;
opacity: 10px;
left: 450px;
top: 300px;
width: 70px;
height: 30px;
position: absolute;
border-radius: 5px;
}

#show .show_hd {
display: block;
left: 0px;
top: 0px;
position: absolute;
border: 1px solid black;
width: 100%;
height: 20px;
}
</style>
</head>


<body>
测试
<input id="btnshow" type="button" value="Show" onclick="showdiv();" />
<div id="div_hs" style="width: 100px;border: 1px solid red;">aaa</div>
<div id="bg"></div>
<div id="show">
<div class="show_hd" id="show_hd">
头部
</div>



<input id="btnclose" type="button" value="Close" onclick="hidediv();" />
</div>
</body>


</html>


上面的程序如果不加window.onload 会报错(FF  fireBUG),因为引擎会从上到下加载,不加window.onload 会报clk为空,因为不加找不到clk ,原因是DOM树找不到show_hd;



<!DOCTYPE html><html> <head>  <meta charset="gb2312" />  <title></title>  <style>   #div1{    width:200px;    height:200px;    background:#ccc;   }  </style>  <script>  window.onload=function change(a,b)  {   var odiv=document.getElementById('div1');   odiv.style[a]=b;  }  </script> </head> <body> <input type="button" value="变宽" onclick="change('width','300px')"/> <input type="button" value="变高" onclick="change('height','300px')"/> <input type="button" value="变黑" onclick="change('background','black')"/> <div id="div1">   </div> </body></html>


这个加了 window.onload反而多余,因为onclick会直接去调用,不必等到全部加载完


0 0
原创粉丝点击