在 jQuery 中切换 2 个类的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7002039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:40:36  来源:igfitidea点击:

Easiest way to toggle 2 classes in jQuery

jquerytoggleclass

提问by Stewie Griffin

If I have class .A and class .B and want to switch in between on button click, what's a nice solution for that in jQuery? I still don't understand how toggleClass()works.

如果我有 class .A 和 class .B 并且想在单击按钮时在两者之间切换,那么在 jQuery 中有什么好的解决方案?我仍然不明白是如何toggleClass()工作的。

Is there an inline solution to put it in onclick=""event?

是否有内联解决方案将其放入onclick=""事件中?

回答by Frédéric Hamidi

If your element exposes class Afrom the start, you can write:

如果您的元素A从一开始就公开类,您可以编写:

$(element).toggleClass("A B");

This will remove class Aand add class B. If you do that again, it will remove class Band reinstate class A.

这将删除 classA并添加 class B。如果您再次这样做,它将删除 classB并恢复 class A

If you want to match the elements that expose either class, you can use a multipleclass selectorand write:

如果要匹配公开任一类的元素,可以使用类选择器并编写:

$(".A, .B").toggleClass("A B");

回答by Rion Williams

Here is a simplified version:(albeit not elegant, but easy-to-follow)

这里是一个简化的版本:虽然不是优雅,但易于后续

$("#yourButton").toggle(function() 
{
        $('#target').removeClass("a").addClass("b"); //Adds 'a', removes 'b'

}, function() {
        $('#target').removeClass("b").addClass("a"); //Adds 'b', removes 'a'

});

Alternatively, a similar solution:

或者,类似的解决方案:

$('#yourbutton').click(function()
{
     $('#target').toggleClass('a b'); //Adds 'a', removes 'b' and vice versa
});

回答by vsync

I've made a jQuery plugin for working DRY:

我制作了一个用于 DRY 的 jQuery 插件:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

You can just try it here, copy and run this in the console and then try:

您可以在这里尝试,在控制台中复制并运行它,然后尝试:

$('body').toggle2classes('a', 'b');

回答by gdibble

Your onClickrequest:

您的onClick要求:

<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>

Try it: https://jsfiddle.net/v15q6b5y/

试试看:https: //jsfiddle.net/v15q6b5y/



Just the JS à la jQuery:

只是 JS à la jQuery

$('.selector').toggleClass('A', !state).toggleClass('B', state);

回答by Luca Reghellin

Here's another 'non-conventional' way.

这是另一种“非常规”的方式。

  • It implies the use of underscoreor lodash.
  • It assumes a context where you:
    • the element doesn't have an init class (that means you cannot do toggleClass('a b'))
    • you have to get the class dynamically from somewhere
  • 它意味着使用下划线lodash
  • 它假定您在以下上下文中:
    • 该元素没有 init 类(这意味着您不能执行 toggleClass('a b'))
    • 你必须从某个地方动态获取类

An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).

这种情况的一个例子可能是具有要在另一个元素(例如容器中的选项卡)上切换的类的按钮。

// 1: define the array of switching classes:
var types = ['web','email'];

// 2: get the active class:
var type = $(mybutton).prop('class');

// 3: switch the class with the other on (say..) the container. You can guess the other by using _.without() on the array:
$mycontainer.removeClass(_.without(types, type)[0]).addClass(type);

回答by Overcomer

The easiest solution is to toggleClass()both classes individually.

最简单的解决方案是toggleClass()单独使用两个类。

Let's say you have an icon:

假设您有一个图标:

    <i id="target" class="fa fa-angle-down"></i>

To toggle between fa-angle-downand fa-angle-updo the following:

要在两者之间切换fa-angle-downfa-angle-up执行以下操作:

    $('.sometrigger').click(function(){
        $('#target').toggleClass('fa-angle-down');
        $('#target').toggleClass('fa-angle-up');
    });

Since we had fa-angle-downat the beginning without fa-angle-upeach time you toggle both, one leaves for the other to appear.

由于我们fa-angle-down在开始时没有fa-angle-up每次切换两者时,一个离开,另一个出现。

回答by Love Kumar

Toggle between two classes 'A' and 'B' with Jquery.

使用 Jquery 在两个类“A”和“B”之间切换。

$('#selecor_id').toggleClass("A B");

$('#selecor_id').toggleClass("A B");