window.onload的作用
写在head标签里面的script可以在window.onload方法里,这样浏览器就会在页面加载完成后再执行script代码。
下面举个例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box {
width: 200px;
height: 200px;
background-color: cadetblue;
margin: 0 auto;
}
</style>
<script>
window.onload = function () {
var falg = true;
var btn = document.getElementById("btn").onclick = function () {
if(falg == true) {
document.getElementById("box").style.width = "400px";
document.getElementById("box").style.height = "400px";
falg = false;
}else {
document.getElementById("box").style.width = "200px";
document.getElementById("box").style.height = "200px";
falg = true;
}
}
}
</script>
</head>
<body>
<input type="button" name="mybutton" id="btn" value="改变大小">
<div id="box"></div>
</body>
</html>