为什么这里JS代码的位置只能放在最后?

来源:3-5 显示和隐藏(display属性)

幕布斯7253233

2018-08-19 04:27

<!DOCTYPE html>
<html>
<head>  
<meta charset="UTF-8">  
<meta name="viewport" content="width=device-width, initial-scale=1.0">  
<meta http-equiv="X-UA-Compatible" content="ie=edge">  
<title>显示与隐藏</title> 
<style type="text/css">  
  body{font-size: 12px;}  
  #txt{height: 400px;width: 600px;border: 1px solid #333;padding: 5px;} 
  p{line-height: 18px;text-indent:2em;}  
</style>
</head>
<body> 
 <h2 id="con">JSSENIE</h2>  
 <div id="txt">  
  <h5>主要内容</h5>   
  <p>主要内容1</p><p>主要内容2</p><p>主要内容3</p> 
 </div>  
<form >  
  <input type="button" value="change color" onclick="changecolor()">     
  <input type="button" value="change size" onclick="changesize()">      
  <input type="button" value="hide text" onclick="hide()">         
  <input type="button" value="show text" onclick="show()">            
  <input type="button" value="reset all" onclick="resetall()"> 
</form> 
<script type="text/javascript">  
 var content=document.getElementById('txt'); 
  function changecolor(){  
    content.style.color="red";   
    content.style.backgroundColor="#ccc";  } 
  function changesize(){ content.style.width="200px"; content.style.height="200px";} 
  function hide(){ content.style.display="none";} 
  function show(){ content.style.display="block";} 
  function resetall(){  
     var mychose=confirm("你确定重置吗?");  
     if (mychose==true){      
      content.removeAttribute("style")   
      } 
     } 
</script>
</body>
</html>

js部分放在了body后面,才运行成功

放在head里面,失败

放在body的前半部分,也失败,

为什么呢??

写回答 关注

2回答

  • 独木不成林
    2018-08-19 14:35:42
    已采纳

    因为js脚本的加载顺序,你放在头部就会先加载js脚本,那时页面HTML部分还没加载,自然获取不了ID,你的程序也就执行不了,你需要在你的脚本中加入window.onload()命令,这个命令我还不太熟,你去网上看一看怎么用吧.


  • qq_她很美_0
    2018-10-15 10:50:21

    你可以将 var content=document.getElementById('txt');
    放到function函数里,这样就不用考虑JS位置了

JavaScript入门篇

JavaScript做为一名Web工程师的必备技术,本教程让您快速入门

738651 学习 · 9561 问题

查看课程

相似问题