jQuery:通过一组类来旋转元素 [英] jQuery: Rotating elements through a set of classes

查看:142
本文介绍了jQuery:通过一组类来旋转元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

toggleClass 是伟大的,如果我只有两个演示文稿样式我想使用,但很多时候我有两个以上的状态,我想使用。



例如,如果我要旋转三个类:

  if($(this).hasClass(A))
$(this).removeClass(A)。addClass(B);
else if($(this).hasClass(B))
$(this).removeClass(B)addClass(C);
else if($(this).hasClass(C))
$(this).removeClass(C)addClass(A);

我想有一个简单的方法为我做这个, >

  $(this).rotateClass('A','B','C');有没有一个现有的jQuery方法或插件?


解决方案

这里是我使用的:

  $。fn.rotateClass = function(classes){
var $ set = this.each(function(){
var $ this = $(this);
var index =(($ this.data currentClassIndex))?$ this.data(currentClassIndex):0)%classes.length;

$ this.removeClass(classes.join())
.addClass classes [index])
.data(currentClassIndex,++ index);
});

return $ set;
}

没有for循环,没有hasClass调用,和非常性能。



用法:

  $(#randomDiv)。rotateClass ([classA,classB,classC,classD]); 


toggleClass is great if I just have two presentations styles I want to use, but a lot of times I've got more than two states that I want to use.

For example, if I want to rotate through three classes:

if ($(this).hasClass("A"))
   $(this).removeClass("A").addClass("B");
else if ($(this).hasClass("B"))
   $(this).removeClass("B").addClass("C");
else if ($(this).hasClass("C"))
   $(this).removeClass("C").addClass("A");

I'd like to have a simple method that did this for me, something like:

$(this).rotateClass('A', 'B', 'C');

Is there an existing jQuery method or plugin that does this?

解决方案

Here's what I use:

$.fn.rotateClass = function(classes) {
    var $set = this.each(function () {
        var $this = $(this);
        var index = (($this.data("currentClassIndex")) ? $this.data("currentClassIndex") : 0) % classes.length;

        $this.removeClass(classes.join(" "))
             .addClass(classes[index])
             .data("currentClassIndex", ++index);
    });

    return $set;
}

No for loops, no hasClass calls, compatible with sets of elements, very compact and very performant.

Usage:

$("#randomDiv").rotateClass(["classA", "classB", "classC", "classD"]);

这篇关于jQuery:通过一组类来旋转元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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