简体   繁体   English

通过单击另一个元素将类切换到一个元素

[英]Toggle class to an element by click another element

I want to click on an element to toggle a class being referenced on a completely unrelated element (not a child, parent or sibling) 我想单击一个元素来切换在完全不相关的元素(不是子元素,父元素或同级元素)上引用的类

For example, initially the code would look like this 例如,最初的代码如下所示

<a id="button">Button</a>

<div class="navigation">
Foo
</div>

When the user clicks the element with the id button the HTML would change to look like this (the class "open" is referenced on element with "navigation" already referenced": 当用户单击带有id button的元素时,HTML将会变为如下所示(在已引用“导航”的元素上引用了“ open”类”:

<a id="button">Button</a>

<div class="navigation open">
Foo
</div>

The user should be able to toggle the class by clicking the element with the id button . 用户应该能够通过单击带有id button的元素来切换类。

I would like to use pure javascript to achieve this effect. 我想使用纯JavaScript来达到此效果。

You could attach click event to the button with id button then on click select the element with class navigation using getElementsByClassName() (ti will return list of nodes) then select the first one using [0] then use toggle() : 您可以将click事件附加到带有id button然后单击使用getElementsByClassName()选择带有类navigation的元素(ti将返回节点列表),然后使用[0]选择第一个元素,然后使用toggle()

document.getElementById('button').onclick = function(){
     document.getElementsByClassName('navigation')[0].classList.toggle("open");
} 

Hope this helps. 希望这可以帮助。


 document.getElementById('button').onclick = function(){ document.getElementsByClassName('navigation')[0].classList.toggle("open"); } 
 .open{ background-color: green; color: white; } 
 <a id="button">Button</a> <div class="navigation"> Foo </div> 

You need to add event handlers. 您需要添加事件处理程序。 This can be done by simple setting the onClick property on the Element object: 这可以通过简单地在Element对象上设置onClick属性来完成:

document.getElementById('button').onClick = function onClick() {
  document.getElementsByClassName('navigation')[0].className += 'open';
};

However, it's preferable that you use addEventListener so multiple event listeners can be added to the same element: 但是,最好使用addEventListener以便可以将多个事件侦听器添加到同一元素:

document.getElementById('button').addEventListener('click', function onClick() {
  document.getElementsByClassName('navigation')[0].className += 'open';
}, false);

EDIT: It's also better to cache your element references in variables like so: 编辑:最好在变量中缓存元素引用,如下所示:

var button = document.getElementById('button');
var nav = document.getElementsByClassName('navigation')[0];

button.addEventListener('click', function onClick() {
  nav.className += 'open';
}, false);

EDIT2: as in Zakaria's answer, you may want to use classList.add(x) instead of className += x . EDIT2:正如Zakaria的回答一样,您可能要使用classList.add(x)而不是className += x It's more in line with how jQuery's things work. 它更符合jQuery的工作方式。 However, be aware that classList is not supported in older versions of IE. 但是,请注意,旧版本的IE不支持classList

EDIT3: Here's a final version using classList.toggle EDIT3:这是使用classList.toggle的最终版本

var button = document.getElementById('button');
var nav = document.getElementsByClassName('navigation')[0];

button.addEventListener('click', function onClick() {
  nav.classList.toggle('open');
}, false);

And here's a quick replacement for classList using className instead: 这是使用className代替classList的快速替代:

function classList(elem) {
  var cl = {
    add: function (clas) { 
      elem.className += clas; 
    },
    remove: function (clas) { 
      elem.className = elem.className.replace(clas, ''); 
    },
    toggle: function (clas) {
      if (elem.className.indexOf(clas) > -1) {
        cl.remove(clas);
      } else {
        cl.add(clas);
      }
    }
  };
  return cl;
}

// usage
classList(nav).add('open');
classList(nav).toggle('open');

You don't really need javascript. 您真的不需要JavaScript。 Checkboxes work great at storing on/off state. 复选框非常适合存储开/关状态。 You just need to get a little crafty with the CSS to use it elsewhere. 您只需要对CSS有所了解即可在其他地方使用它。 Here is an example: 这是一个例子:

 label.divcheck { color:blue; text-decoration:underline; } input.divcheck { display:none; } input.divcheck + div { display:none; } input.divcheck:checked + div { display:block;} 
 <label class="divcheck" for="navigation">Button Nav</label> <label class="divcheck" for="other">Button Other</label> <input type="checkbox" class="divcheck" id="navigation"/> <div class="navigation"> Foo </div> <input type="checkbox" class="divcheck" id="other"/> <div class="navigation"> Other </div> 

Try this: 尝试这个:

document.querySelector('div.navigation').classList.toggle('open');

This will work if you only have one div element that has the class navigation. 如果只有一个具有类导航的div元素,则此方法将起作用。 It would be better to give it an id, for example id=navigation 最好给它一个id,例如id = navigation

Multiple elements with class navigation 具有类navigation多个元素

navigation is a class, so I assume there is more than one element you would like to give class open on click on element with id button . navigation是一个类,因此我假设您想通过单击带有id button元素来open类,不只一个元素。 Do it that way: 这样做:

 function toggleNavigation(element) { element.classList.toggle('open'); } document.getElementById('button').addEventListener('click', function() { Array.from(document.getElementsByClassName('navigation')).forEach(toggleNavigation); }); 
 .navigation { background-color: lightgreen; } .navigation.open { background-color: lightblue; } 
 <a id="button">Button</a> <div class="navigation">Foo</div> <div class="navigation">Foo</div> <div class="navigation">Foo</div> 

Single element with class or id navigation 具有类或ID navigation单个元素

If it is otherwise (ie, there is only one element with class navigation , in which case it should be an id, not a class) you can replace above JavaScript to: 如果不是这样(例如,类navigation只有一个元素,在这种情况下,它应该是一个id而不是一个类),则可以在JavaScript上方替换为:

document.getElementById('button').addEventListener('click', function() {
  document.getElementsByClassName('navigation')[0].classList.toggle('open');
});

or if you will change navigation to be an id: 或者,如果您将navigation更改为ID:

document.getElementById('button').addEventListener('click', function() {
  document.getElementById('navigation').classList.toggle('open');
});

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

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