gpt4 book ai didi

javascript - 如何在不重复的情况下随机浏览未知数量的报价

转载 作者:行者123 更新时间:2023-11-30 18:02:21 24 4
gpt4 key购买 nike

我有一小段 Javascript,我在其中按顺序从头到尾轮换引用列表。

但是,我想随机浏览列表(而不是按顺序),直到所有引号都被遍历,然后再从随机引号开始。我该怎么做呢?

$(function(){
var quotes = $('#quotes').children('.rotate-quote');
firstQuo = quotes.filter(':first');
lastQuo = quotes.filter(':last');
quotes.first().show();
setInterval(function(){
if($(lastQuo).is(':visible')) {
var nextElem = $(firstQuo);
} else {
var nextElem = $(quotes).filter(':visible').next();
}
$(quotes).filter(':visible').fadeOut(300);
if($(lastQuo).is(':visible')) {
setTimeout(function() {
$(firstQuo).fadeIn(300);
}, 600);

} else {
setTimeout(function() {
$(nextElem).fadeIn(600);
}, 600);
}
}, 10000);
});

最佳答案

这是一个可能的演示解决方案:

var $container = $('div'),
quotes = $('quote').hide().toArray(),
delay = 500;

function shuffle(arr) {
return arr.map(function(v){ return [v,Math.random()]; })
.sort().map(function(v){ return v[0]; });
}

function loop() {
$(shuffle(quotes)).each(function(i,el) {
setTimeout(function(){ $(el).appendTo($container).show(); }, i*delay);
});
}

function start() {
function begin(){ $(quotes).hide(); loop(); }
setInterval(begin, quotes.length * delay);
begin();
}

start();

演示: http://jsbin.com/agihix/1/edit

编辑:我把它变成了一个小插件,在这里抓取它https://gist.github.com/elclanrs/5610886

关于javascript - 如何在不重复的情况下随机浏览未知数量的报价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16642877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com