作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一小段 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/
我是一名优秀的程序员,十分优秀!