jquery timed change of item class

2020-06-26 11:17发布

Is it possible to change an items class or ID based on some type of timer? Every 1500ms it would go to hey-there-1, then 1500ms later hey-there-2.. etc.. something that I could possibly control how many intervals it goes through..

  • hey-there
  • hey-there-1
  • hey-there-2
  • hey-there-3
  • (back to beginning) hey-there
  • etc

Thanks

标签: jquery
3条回答
冷血范
2楼-- · 2020-06-26 11:40

A plugin function as such will allow you to do what you want:

jQuery.fn.rotateClasses = function(classes, interval, max) {
    var currentRotation = 0;
    var timer = null;

    var rotateFn = (function() {
            var currentClass = currentRotation % classes.length;

        var previousClass = currentClass - 1;
        if(previousClass == -1) previousClass = classes.length - 1;

        this.addClass(classes[currentClass]).removeClass(classes[previousClass]);

        currentRotation += 1;

            if(max > 0 && currentRotation >= max) clearInterval(timer);
    })();

    timer = setInterval(rotateFn, interval);

    return this;
};

Then you can simply call it using the following:

$('#mydiv').rotateClasses(["class1", "class2", "class3"], 1000, 20);

Simply modify the parameters as you wish. First parameter is an array of classes to rotate, second is the interval to rotate them to, and the third is the maximum number of iterations. If set to 0, it iterates ad-infinitum.

查看更多
3楼-- · 2020-06-26 11:59

See:

setTiemOut
setInternal

var pp = 0;

jQuery("#id").html(jQuery("#id").html() + "<div>hey there"+(pp++)+"</div>");
查看更多
相关推荐>>
4楼-- · 2020-06-26 12:01

I would suggest against changing the ID of the element - instead go for "frame1/frame2/frame3" classes.

$(function() {
  var $target = $("#hey-there");
  var classes = ['frame0', 'frame1', 'frame2', 'frame3'];
  var current = 0;

  setInterval(function() {
    $target.removeClass(classes[current]);
    current = (current+1)%classes.length;
    $target.addClass(classes[current]);
  }, 1500); // 1500 ms loop
});
查看更多
登录 后发表回答