我的HTML正文中有<h1>
标记,我希望每次用户点击它时都会根据我在名为ShowIt()
的javascript函数中定义的条件做出反应。第一次单击将显示隐藏部分,第二次单击将重新隐藏它,来回切换。但是,我无法让它发挥作用。
*{
margin:0;
padding:0;
}
header,section,nav,aside,footer{
display: block;
}
.wrapper{
position: relative;
width: 1000px;
height: 4000px;
margin: 0 auto;
}
#hid{
background-color: #FF9;
color: #000;
font-size: 25px;
font-family: Arial;
width: 200px;
height: 200px;
position: absolute;
top: 1200px;
display:none;
}
h1{
cursor: pointer;
color: #000;
font-size: 25px;
font-family: Arial;
position: absolute;
top: 1150px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="includes/style.css">
<script src="includes/script.js"></script>
<title>Some JS</title>
<script>
window.onload=function(){
function ShowIt(){
var obj = document.getElementById("hid");
if(obj.style.display == "block")
obj.style.display = "none";
else
obj.style.display = "block";
};
}
</script>
</head>
<body>
<div class="wrapper">
<section id="hid">hidden layer</section>
<h1 onclick="ShowIt">click here</h1>
</div>
</body>
</html>
答案 0 :(得分:2)
您在ShowIt
函数中定义了window.onload
函数,这不起作用,因为ShowIt
的范围不是全局的。
<script>
function ShowIt(){
var obj = document.getElementById("hid");
if(obj.style.display == "block")
obj.style.display = "none";
else
obj.style.display = "block";
};
</script>
<div class="wrapper">
<section id="hid">hidden layer</section>
<h1 onclick="ShowIt()">click here</h1>
</div>
答案 1 :(得分:2)
您的功能应在window.onload
之外宣布,否则您将获得范围问题。
一些JS
<script>
function ShowIt(){
var obj = document.getElementById("hid");
if(obj.style.display == "block")
obj.style.display = "none";
else
obj.style.display = "block";
};
</script>
</head>
<body>
<div class="wrapper">
<section id="hid">hidden layer</section>
<h1 onclick="ShowIt()">click here</h1>
</div>
</body>
要调用该功能,您需要执行以下操作:ShowIt()