[英]Change the class of a Button element to show/hide it
我试图根据我的代码中的某些条件显示或隐藏按钮元素。 我已经使按钮的默认css用display: none
“隐藏”它,然后添加一个更改显示的类: display: block
。
HTML:
<div>
<button id="show">SHOW</button>
</div>
CSS:
#show {
display: none;
}
#show .visible {
display: block;
}
JS:
var d = document.getElementById('show');
d.className += "visible";
我也尝试过:
var d = document.getElementById('show');
d.classList.add("visible");
以及:
documnet.getElementById('show').classList.add('visible');
问题是我无法正确应用类,并且在更新类时不会显示按钮。 我敢肯定,我忽视了一些简单的事情,只是不确定如果有人可以提供帮助的话。
您将该类“显示”在具有id“show”的同一元素上。
所以在你的CSS中,#show和.visible之间不应该有空格。
HTML
<div>
<button id="show">SHOW</button>
</div>
CSS
#show {
display: none;
}
#show.visible {
display: block;
}
JS
var d = document.getElementById('show');
d.classList.add("visible");
请使用这种方法!
而不是更改ID的切换类hide
以便按钮可见或不可见!
function myFunction() { var element = document.getElementById("show"); element.classList.toggle("hide"); }
.hide{ display:none; } #show{ display: block; }
<div> <button id="show">SHOW</button> </div> <button onClick="myFunction()">Toggle</button>
简单。 写这个:
#show.visible {
display: block;
}
代替:
#show .visible {
display: block;
}
(只需删除你在#show和.visible之间放置的空间 )
document.getElementById('show').classList.add('visible');
#show { /*display: none;*/ } .invisible{ display: none; } .visible { display: block; }
<div> <button id="show" class="invisible">SHOW</button> </div>
我想推荐使用2门课程。 .visible
, .invisible
。
你应该在.invisible
上设置display:none
。 #show
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.