单击jQuery切换类 [英] jQuery switch classes on click

查看:66
本文介绍了单击jQuery切换类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WordPress网站,其中有一些管道"元素,我希望在单击这些元素时更改颜色.我是jQuery新手,因此需要一些帮助.到目前为止,这就是我所拥有的(这是非常简化的版本):

I have a WordPress site where I have some "pipe" elements which I want to change color when clicked. I'm new to jQuery so I would need some help to do this. This is what I have so far (a very simplified version of it all):

jQuery:

jQuery(function() {
  jQuery(".--clearGreen").click(function() {
    jQuery(this).addClass("--clearGreenClicked");
  });
});

CSS:

.--clearGreen {
 background-color: rgba(255, 255, 255, 0);
 border: 2px solid green;
}

.--clearGreenClicked {
 background-color: blue;
 border: 2px solid blue;
 color: white;
}

这可以将.--clearGreenClicked类添加到我在页面上单击的.--clearGreen管道"中.我要实现的目标是,使仅单击的管道"得到应用的更改,所有其他管道"恢复到原始样式,从而基本上使它们根据管道"进行切换"样式单击.我尝试将.not.has结合使用,但似乎无法使其正常工作.谢谢!

This works to add the .--clearGreenClicked class to the clicked .--clearGreen "pipe" that I have on the page. What I would like to achieve is to make it so that only the clicked "pipe" gets the change applied to it and all the other "pipes" return to the original styling, so basically that they "switch" styles depending on what "pipe" is clicked. I've tried to use .not in combination with .has but I can't seem to get it to work properly. Thanks!

推荐答案

措辞:

仅单击的管道获得了更改,其他管道[保留]保留了原始样式"

only the clicked pipe gets the change and the other pipes [remain] with the original styling"

您的代码正是这样做的,因为您使用过$(this).addClass.

your code does exactly that, because you've used $(this).addClass.

因此,假设您要询问以及其他管道还原为原始样式",那么一次只能选择"一个管道:

So assuming you're asking "and the other pipes return to the original styling", so only one is "selected" at a time:

jQuery(function() {
  jQuery(".--clearGreen").click(function() {
    jQuery(".--clearGreenClicked").removeClass("--clearGreenClicked");
    jQuery(this).addClass("--clearGreenClicked");
  });
});


其他:


Additional:

您可以使用.not减少所做的更改,例如:

You can use .not to reduce the changes made, eg:

jQuery(".--clearGreenClicked").not(this).removeClass("--clearGreenClicked");
jQuery(this).addClass("--clearGreenClicked");

这将停止删除代码,然后重新添加类-如果您在CSS上使用transition,则可能会有所不同.

which will stop the code from removing and then re-adding the class - this could make a difference if you have a transition on the css.

这篇关于单击jQuery切换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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