Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't really need javascript. Checkboxes work great at storing on/off state. You just need to get a little crafty with the CSS to use it elsewhere. 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...