[英]How do you toggle the visibility of an html element in Javascript?
I was wondering if anyone could figure out why my function won't work properly. 我想知道是否有人能弄清楚为什么我的功能无法正常工作。 What I am trying to achieve is when a button is clicked it displays text and when it is clicked again it hides it and so on.
我想要实现的是当点击一个按钮时它会显示文本,当它再次被点击时它会隐藏它,依此类推。
function hideshow (){
var showhide=document.getElementById('text');
if(showhide.style.display="none")
{
showhide.style.display="block";
}
else{
showhide.style.display="none";
}
}
So far I got it to display my text when I click it once, but once I click it again it has no effect on the text. 到目前为止,当我点击它时,我得到了它来显示我的文本,但是一旦我再次点击它,它对文本没有影响。
I believe that should be: 我认为应该是:
function hideshow (){
var showhide = document.getElementById('text');
if (showhide.style.display == "none")
{
showhide.style.display = "block";
}
else{
showhide.style.display = "none";
}
}
So, use '==' instead of '=' when comparing. 因此,在比较时使用'=='而不是'='。 The '=' operator assigns a value.
'='运算符赋值。 In javascript there is also the '===' operator.
在javascript中还有'==='运算符。 The difference is that '==' will cast values, while '===' will compare strictly.
区别在于'=='将投射值,而'==='将严格比较。
For example: 例如:
0 == false; // will return true
0 === false; // will not
So you can also use 所以你也可以使用
if (showhide.style.display === "none")
you should be using ===
in your if
statment. 你应该在你的
if
语句中使用===
。 =
is an assignment operator: =
是赋值运算符:
function hideshow (){
var showhide=document.getElementById('text');
if(showhide.style.display==="none")
{
showhide.style.display="block";
}
else{
showhide.style.display="none";
}
}
Or: 要么:
function hideshow (){
var showhide=document.getElementById('text');
showhide.style.display = showhide.style.display === "none" ?
"block" :
"none";
}
You should be using the comparison ==
operator instead of assigning the value using the =
operator. 您应该使用比较
==
运算符,而不是使用=
运算符分配值。
Try: 尝试:
function hideshow() {
var showhide = document.getElementById('text').style;
(showhide.display = showhide.display == "none" ? "block" : "none" )
}
You can assign and compare in one statement using: 您可以使用以下命令在一个语句中分配和比较
(showhide.display = showhide.display == "none" ? "block" : "none" )
^assign ^comparison
Demo: http://jsfiddle.net/7Eaf2/ 演示: http : //jsfiddle.net/7Eaf2/
function hideShow() {
el.style.display != "none" ? "none" : "block";
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function hideshow() {
var showhide=document.getElementById('text');
if(showhide.style.visibility=="hidden")
{
showhide.style.visibility="visible";
}
else{
showhide.style.visibility="hidden";
}
}
</script>
</head>
<body>
<div id="text">Text</div>
<button onclick="hideshow()">hideshow</button>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.