【问题标题】:Shuffle jQuery selection随机播放 jQuery 选择
【发布时间】:2014-09-09 23:47:00
【问题描述】:

我正在尝试打乱 jQuery 选择的顺序不打乱 DOM 中的元素

我需要打乱选择,以随机顺序为每个元素添加一个类,这就是我的代码的外观:

$(".item").shuffle().each(function (i, element) {
    $(element).delay(i * 100).queue(function (next) {
        $(this).addClass("shown");
        next();
    });
});

谁能帮我找到我需要的shuffle()函数?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

我从this answer借用了Array.shuffle的方法,做成了一个jQuery插件

$.fn.shuffle = function(){
    for(var j, x, i = this.length; i; j = Math.floor(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
    return this;
};

FIDDLE

【讨论】:

  • 我不认为数组洗牌会这样做,看起来洗牌会在 html 元素上完成。
  • @superUntitled - 这就是为什么我修改它以用于 jQuery 集合
【解决方案2】:
$.fn.shuffle = function () {
    'use strict';
    var self = this,
        i,
        rnd,
        len = self.length - 1;
    for (i = len; i > 0; i -= 1) {
        rnd = Math.floor(Math.random() * len) % i;
        [self[i], self[rnd]] = [self[rnd], self[i]];
    }
    return self;
}

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 2013-03-06
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多