为什么JS必须全部写在window.onload中,页面才能实现?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding:0;}
.head{font-size:12px;padding:6px 0 0 10px;}
#login_box{width:300px;height:150px;background:#eee;
border:1px solid #ccc;position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;display:none;}
#login_box p{height:20px;border-bottom:1px solid #ccc;font-size:12px;padding:6px 0 0 5px;font-weight:bold;}
#close{width:14px;height:14px;position:absolute;right:4px;top:6px;cursor:pointer;}
</style>
<script>
window.onload = function(){
var login_btn=document.getElementById('login'),
login_box=document.getElementById('login_box'),
close=document.getElementById('close');
// 封装添加事件监听程序
var eventUtil = {
addHandler:function(ele,type,hander) {
// 执行代码
if (ele.addEventListener) {
ele.addEventListener(type,hander,false);
}
else if (ele.attachEvent) {
ele.attachEvent("on"+type,hander);
}
else {
ele["on"+type] = hander;
}
}
}
// 显示登录层函数
function showLogin() {
// 执行代码
login_box.style.display = "block";
}
// 隐藏登录层函数
function hideLogin() {
// 执行代码
login_box.style.display = "none";
}
//点击登录按钮显示登录层
// 执行代码
eventUtil.addHandler(login_btn,"click",showLogin);
eventUtil.addHandler(close,"click",hideLogin);
//点击关闭按钮隐藏登录层
// 执行代码
}
</script>
</head>
<body>
<div>亲,您好!<input type="button" value="登 录" id="login"></div>
<div id="login_box">
<p>用户登录</p><span id="close">X</span>
<div style="display:table;margin:20px ;">
<div style="display:table-row">
<span style="display:table-cell;text-align:right;vertical-align:middle;">用户名:</span><span style="display:table-cell;"><input type="text" placeholder="请输入用户名" style="height:50px;"></span>
</div>
<div style="display:table-row">
<span style="display:table-cell;text-align:right;vertical-align:middle;">密码:</span><span style="display:table-cell"><input type="text" placeholder="请输入密码"></span>
</div>
</div>
</div>
</body>
</html>
望大神指点,谢谢!!