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>

看懂了吧  哈哈哈!!!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM