<!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的前半部分,也失败,
为什么呢??
因为js脚本的加载顺序,你放在头部就会先加载js脚本,那时页面HTML部分还没加载,自然获取不了ID,你的程序也就执行不了,你需要在你的脚本中加入window.onload()命令,这个命令我还不太熟,你去网上看一看怎么用吧.
你可以将 var content=document.getElementById('txt'); 放到function函数里,这样就不用考虑JS位置了