标签:style 一段 put load script rip 找不到 blog 执行
前端页面加载是从上往下,从左往右的顺序进行的,如果需要在整个页面加载完成之后再执行需要被执行的js代码,就可以使用window.onload了;
1.看下面一段代码,这段代码在执行的时候是有问题的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#box{
width: 100px;
height: 100px;
background: #f00;
}
</style>
<script>
// alert(document.getElementById(‘btn‘)); //null,表示取到的对象为空
document.getElementById(‘btn‘).onclick = function(){
document.getElementById(‘box‘).style.width = ‘200px‘;
document.getElementById(‘box‘).style.height = ‘200px‘;
};
</script>
</head>
<body>
<input type="button" name="btn" id="btn" value="按钮" />
<div id="box"></div>
</body>
</html>
原因: 页面中的代码一般会从上到下,从左到右的顺序执行;当代码走到18行的时候,会从页面中的id为btn的元素,,但是下面的代码还没有执行,所以他找不到,这样的话就会报错;
解决:window.onload = function(){当页面中的代码都加载完成之后,执行这里的代码;}
2、正确代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#box{
width: 100px;
height: 100px;
background: #f00;
}
</style>
<script>
// alert(document.getElementById(‘btn‘)); //null,表示取到的对象为空
window.onload = function(){
document.getElementById(‘btn‘).onclick = function(){
document.getElementById(‘box‘).style.width = ‘200px‘;
document.getElementById(‘box‘).style.height = ‘200px‘;
};
};
</script>
</head>
<body>
<input type="button" name="btn" id="btn" value="按钮" />
<div id="box"></div>
</body>
</html>
标签:style 一段 put load script rip 找不到 blog 执行
原文地址:http://www.cnblogs.com/cqq-20151202/p/6592821.html