通过点击另一个元素将类切换为元素 [英] Toggle class to an element by click another element

查看:64
本文介绍了通过点击另一个元素将类切换为元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想点击一个元素来切换一个完全不相关的元素(不是孩子,父母或兄弟姐妹)引用的类。

例如,最初代码看起来像这样

 < a id =button>按钮< / a> 

< div class =navigation>
Foo
< / div>

当用户点击id 按钮 HTML会变成看起来像这样的类(open在引用了navigation的元素上被引用过了:

 < a id =button>按钮< / a> 

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

用户应该可以通过点击ID 按钮



我想用纯javascript来达到这个效果。

点击事件附加到ID 按钮按钮上,然后点击使用 getElementsByClassName()(ti将返回节点列表),选择带有类导航的元素,然后选择第一个一个使用 [0] 然后使用 toggle()

 的document.getElementById( '按钮')。Ô nclick = function(){
document.getElementsByClassName('navigation')[0] .classList.toggle(open);
}

希望这有助于您。

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

.open {background-颜色:绿色; color:white;}

< a id =button >按钮< / a>< div class =navigation> Foo< / div>

b $ b

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":

<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.

I would like to use pure javascript to achieve this effect.

解决方案

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() :

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>

这篇关于通过点击另一个元素将类切换为元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆