简体   繁体   English

如何更改A的属性 <div> 切换班级?

[英]How do I change the properties of a <div> with a toggled class?

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. 我有一个<div class="content toggle"> ,在某个事件被调用之前,我一直将其隐藏起来,然后向其中添加一个类以表明它需要可见。

My current CSS looks like: 我当前的CSS看起来像:

.content {
  display: none;
}

.content.visible {
  display: block;
}

My code for adding .visible looks like this: 我添加.visible代码如下所示:

[].forEach.call(document.getElementsByClassName('toggle'), function(x) {
  x.classList.toggle('visible');
});

But, when the class .visible is added, the <div> is still display: none; 但是,当添加类.visible时, <div>仍然display: none; . What's happening here? 这里发生了什么事? How can I fix it? 我该如何解决?

似乎您的JS选择了一个名为“ toggle”而不是“ content”的类:

getElementsByClassName('toggle')

There's 100 ways do what you want. 有100种方法可以满足您的需求。 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. 更新了答案,以反映jsfiddle。

HTML: HTML:

<div class="content">hi</div>
<button id='button'>toggle visible</button>

JS 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: 在jQuery中:

$(this).toggleClass("visible hidden");

and the css: 和CSS:

<style>
.visible {
   display: block;
}
.hidden {
   display: none;
}
</style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM