I have a <div class="content toggle">
that I have hidden until a certain event is called, and then I add a class to it to show that it needs to be visible.
My current CSS looks like:
.content {
display: none;
}
.content.visible {
display: block;
}
My code for adding .visible
looks like this:
[].forEach.call(document.getElementsByClassName('toggle'), function(x) {
x.classList.toggle('visible');
});
But, when the class .visible
is added, the <div>
is still display: none;
. What's happening here? How can I fix it?
似乎您的JS选择了一个名为“ toggle”而不是“ content”的类:
getElementsByClassName('toggle')
There's 100 ways do what you want. Here's one solution.
<script>
function makeVisible() {
var myContentDiv = document.getElementById("mycontent");
myContentDiv.style.display = "block";
}
</script>
<div id="mycontent" class="content"></div>
<a id="mybutton" href="javascript:makeVisible()"></a>
Updated answer, to reflect the jsfiddle.
HTML:
<div class="content">hi</div>
<button id='button'>toggle visible</button>
JS
var button = document.getElementById('button');
button.onclick = function() {
var div = document.getElementById('content');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
.content {
display: none;
}
.visible {
display: block;
}
?
Keep your display classes separate from your core class.
in jQuery:
$(this).toggleClass("visible hidden");
and the css:
<style>
.visible {
display: block;
}
.hidden {
display: none;
}
</style>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.