window.onload事件

网页中的某些JavaScript脚本代码往往需要在文档加载完成后才能够去执行,否则可能导致无法获取对象的情况,为了避免类似情况的发生,可以使用以下两种方式:

(1).将脚本代码放在网页的底端,运行脚本代码的时候,可以确保要操作的对象已经加载完成。

(2).通过window.onload来执行脚本代码。

看完下面两段代码你就能理解上面的意思了

代码一

<!DOCTYPE html>  
<html>  
<head>  
<meta charset=" utf-8">  
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<style type="text/css">
#bg{
  width:100px;
  height:100px;
  border:2px solid red;
}
</style>
</head>
<body>
  <div id="bg"></div>
</body>
</html>

<script type="text/javascript">
document.getElementById("bg").style.backgroundColor="#F90";
</script>

代码二

<!DOCTYPE html>  
<html>  
<head>  
<meta charset=" utf-8">  
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<style type="text/css">
#bg{
  width:100px;
  height:100px;
  border:2px solid red;
}
</style>
<script type="text/javascript">
window.onload=function(){
  document.getElementById("bg").style.backgroundColor="#F90";
}
</script>
</head>
<body>
  <div id="bg"></div>
</body>
</html>

看懂了吧  哈哈哈!!!

猜你喜欢

转载自www.cnblogs.com/chosenone/p/9274140.html