javascript jQuery:在 3 个类之间切换(最初)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14200833/
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-10-26 20:59:27  来源:igfitidea点击:

jQuery: Toggling between 3 classes (initially)

javascriptjquery

提问by Ricardo Zea

I've seen several posts here on SO but they are too specific in functionality and structure, and what I'm looking for is something more universal that I or anyone can use anywhere.

我在这里看到了几篇关于 SO 的帖子,但它们在功能和结构上过于具体,我正在寻找的是我或任何人都可以在任何地方使用的更通用的东西。

All I need is to have a button that when clicked can cycle between 3classes. But if the case arises to have to cycle through 4, 5 or more classes, that the script can be easily scaled.

我所需要的只是有一个按钮,单击该按钮可以在3 个类之间循环。但是,如果出现必须循环遍历 4、5 个或更多类的情况,则可以轻松扩展脚本。

As of this moment I am able to 'cycle' between two classes which is basically more "toggling" than cycling, so for that I have:

到目前为止,我能够在两个类之间“循环”,这基本上比骑自行车更“切换”,因此我有:

HTML:

HTML:

<a href="#" class="toggle">Toggle classes</a>
<div class="class1">...</div>

jQuery:

jQuery:

$('.toggle').click(function () {
  $('div').toggleClass('class1 class2');
});

Here's a simple fiddleof this.

这是一个简单的小提琴

Now, you would (well, I) think that adding a third class to the method would work, but it doesn't:

现在,您会(好吧,我)认为向该方法添加第三个类会起作用,但它不会:

$('div').toggleClass('class1 class2 class3');

What happens is that the toggling starts happening between class1and class3only.

发生的事情是切换开始发生在class1和之间class3

So this is where I have my initial problem: How to have the Toggle button cycle sequentially through 3classes?

所以这就是我最初遇到的问题:如何让 Toggle 按钮按顺序循环通过3 个类?

And then: What if someone needs to cycle to 4, 5 or more classes?

然后:如果有人需要骑自行车上 4 节、5 节或更多课怎么办?

回答by Denys Séguret

You can do this :

你可以这样做 :

$('.toggle').click(function () {
  var classes = ['class1','class2','class3'];
  $('div').each(function(){
    this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
  });
});

Demonstration

示范

回答by user3353523

Here is another approach:

这是另一种方法:

if ($(this).hasClass('one')) {
    $(this).removeClass('one').addClass('two');
} else if ($(this).hasClass('two')) {
    $(this).removeClass('two').addClass('three');
} else if ($(this).hasClass('three')) {
    $(this).removeClass('three').addClass('one');
}

回答by Toddish

var classes = ['class1', 'class2', 'class3'],
    currentClass = 0;

$('.toggle').click(function () {

    $('div').removeClass(classes[currentClass]);

    if (currentClass + 1 < classes.length)
    {
        currentClass += 1;
    }
    else
    {
        currentClass = 0;
    }

    $('div').addClass(classes[currentClass]);

});

Something like that should work OK :)

这样的事情应该可以正常工作:)

Tinker IO link - https://tinker.io/1048b

Tinker IO 链接 - https://tinker.io/1048b

回答by Mr. Polywhirl

I converted user3353523's answerinto a jQuery plugin.

我将user3353523 的答案转换为 jQuery 插件。

(function() {
  $.fn.rotateClass = function(cls1, cls2, cls3) {
    if ($(this).hasClass(cls1)) {
      return $(this).removeClass(cls1).addClass(cls2);
    } else if ($(this).hasClass(cls2)) {
      return $(this).removeClass(cls2).addClass(cls3);
    } else if ($(this).hasClass(cls3)) {
      return $(this).removeClass(cls3).addClass(cls1);
    } else {
      return $(this).toggleClass(cls1); // Default case.
    }
  }
})(jQuery);

$('#click-me').on('click', function(e) {
  $(this).rotateClass('cls-1', 'cls-2', 'cls-3');
});
#click-me {
  width: 5em;
  height: 5em;
  line-height: 5em;
  text-align: center;
  border: thin solid #777;
  margin: calc(49vh - 2.4em) auto;
  cursor: pointer;
}

.unselectable {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
   -khtml-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}

.cls-1 { background: #FFAAAA; }
.cls-2 { background: #AAFFAA; }
.cls-3 { background: #AAAAFF; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="click-me" class="unselectable">Click Me!</div>



Dynamic Approach

动态方法

(function() {
  $.fn.rotateClass = function() {
    let $this = this,
        clsList = arguments.length > 1 ? [].slice.call(arguments) : arguments[0];
    if (clsList.length === 0) {
      return $this;
    }
    if (typeof clsList === 'string') {
      clsList = clsList.indexOf(' ') > -1 ? clsList.split(/\s+/) : [ clsList ];
    }
    if (clsList.length > 1) {
      for (let idx = 0; idx < clsList.length; idx++) {
        if ($this.hasClass(clsList[idx])) {
          let nextIdx = (idx + 1) % clsList.length,
              nextCls = clsList.splice(nextIdx, 1);
          return $this.removeClass(clsList.join(' ')).addClass(nextCls[0]);
        }
      }
    }
    return $this.toggleClass(clsList[0]);
  }
})(jQuery);

$('#click-me').on('click', function(e) {
  $(this).rotateClass('cls-1', 'cls-2', 'cls-3');     // Parameters
  //$(this).rotateClass(['cls-1', 'cls-2', 'cls-3']); // Array
  //$(this).rotateClass('cls-1 cls-2 cls-3');         // String
});
#click-me {
  width: 5em;
  height: 5em;
  line-height: 5em;
  text-align: center;
  border: thin solid #777;
  margin: calc(49vh - 2.4em) auto;
  cursor: pointer;
}

.unselectable {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
   -khtml-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}

.cls-1 { background: #FFAAAA; }
.cls-2 { background: #AAFFAA; }
.cls-3 { background: #AAAAFF; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="click-me" class="unselectable">Click Me!</div>

回答by huan feng

HTML:

HTML:

<div id="example" class="red">color sample</div>

CSS:

CSS:

.red {
  background-color: red;
}
.yellow {
  background-color: yellow;
}
.green {
  background-color: green;
}

JS:

JS:

$(document).ready(function() {
    var colors = ['red', 'yellow', 'green'];
    var tmp;
    setInterval(function(){
        tmp && $('#example').removeClass(tmp);
        tmp = colors.pop();
        $('#example').addClass(tmp);
        colors.unshift(tmp);
    }, 1000);
});

DEMO

演示

回答by H77

Another version that uses classList replace. Not supported by all browsers yet.

另一个使用classList replace. 并非所有浏览器都支持。

var classes = ["class1", "class2", "class3"];
var index = 0;
var classList = document.querySelector("div").classList;
const len = classes.length;

$('.toggle').click(function() {
  classList.replace(classes[index++ % len], classes[index % len]);
});
.class1 {
  background: yellow;
}

.class2 {
  background: orange;
}

.class3 {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="toggle">Toggle classes</a>
<div class="class1">
  look at me!
</div>

回答by user3238363

Cycles through the index of classes and toggles from one to ther other.

在类的索引中循环并从一个切换到另一个。

var classes = ['border-top','border-right','border-bottom','border-left'];
var border = 'border-top';
var index = 0;
var timer = setInterval( function() {
    var callback = function(response) {
        index = ( ++index == 4 ? 0 : index );
        $(element).html("text").toggleClass( border + " " + classes[index] );
        border = classes[index];
        };
    }, 1000 );

回答by user3238363

This worked for me and I can stack as many as I want, then wrap around easily.

这对我有用,我可以随心所欲地堆叠,然后轻松环绕。

switch($('div.sel_object table').attr('class'))
    {
    case "A":   $('div.sel_object table').toggleClass('A B'); break;
    case "B":   $('div.sel_object table').toggleClass('B C'); break;
    case "C":   $('div.sel_object table').toggleClass('C D'); break;
    case "D":   $('div.sel_object table').toggleClass('D A'); break;                
    }