简体   繁体   English

使用 Javascript 单击添加和删除类

[英]Add & Remove Class On Click with Javascript

I actually don't often use Javascript and don't know much about coding with it, so I want to excuse this question, if it is a simple one!我实际上并不经常使用 Javascript 并且对使用它进行编码了解不多,所以我想原谅这个问题,如果它是一个简单的问题!

I have this html elements:我有这个 html 元素:

<button class="btn"></button>

<div class="section1 active" style="z-index:1;"></div>

<div class="section2" style="z-index:2;"></div>

Now I would like to add the class "active" to div .section2 and at the same time to remove this class "active" from div .section1 by clicking on the button .btn .现在我想将类“active”添加到 div .section2 ,同时通过单击按钮 .btn 从 div .section1 中删除此类“active”。

Additionally, on click on button .btn I would like to change the style attribute "z-index:1" from .section1 to "z-index:2" and at the same time to change "z-index:2" from .section2 into "z-index:1"此外,在单击按钮 .btn 时,我想将样式属性“z-index:1”从 .section1 更改为“z-index:2”,同时将“z-index:2”从 .section1 更改为“z-index:2”。第2部分到“z-index:1”

Could someone please give me a full javascript code that would change the classes and style attributes when I click the button?有人可以给我一个完整的 javascript 代码,当我单击按钮时,它会更改类和样式属性吗?

Thank you :)谢谢 :)

 $('.section1').click(function(){ $('.section1').removeClass('active').html('CLICK FOR ACTIVE').css('z-index', 1); $(this).addClass('active').html('ACTIVE').css('z-index', 2); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="section1 active" style="z-index:1;">CLICK FOR ACTIVE</div> <div class="section1" style="z-index:2;">ACTIVE</div>

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

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