我有一个包含 100 个对象的数组列表,我想将它们随机附加到屏幕上。
for (var i = 0; i < theobject.length; i++) {
var item = theobject[Math.floor(Math.random()*theobject.length)];
$('.container').append('<div class="theitem"> item.themessage </div>')
}
好吧,我的目标是在屏幕上一次附加其中五个,然后用“排队列表”上的下一个随机替换这 5 个中的一个。淡出的对象将从 DOM 和对象列表中删除,因此不会再次放置。有什么建议么?非常感谢!
最佳答案
以下是您可以执行的操作:
- 首先根据随机选择对数组进行打乱,而不是从数组中获取随机值。然后你就可以迭代该数组,而不必担心会得到重复项
- 使用 jQuery
animate
方法清除并设置 5 个元素之一的不透明度 - 使用
promise
方法创建一个 Promise,并链接一个then
回调,该回调在动画准备就绪时执行 - 使用
delay
在下一个项目被选择和淡出之前引入一段时间。 - 将其放入自调用函数中以使其无限重复
- 使用
%
运算符实现循环数组遍历
代码:
// Utility function
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
// Some sample data
var theobject = ["Lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua","Ut","enim","ad","minim","veniam","quis","nostrud","exercitation","ullamco","laboris","nisi","aliquip","ex","ea","commodo","consequat","Duis","aute","irure","in","reprehenderit","voluptate","velit","esse","cillum","eu","fugiat","nulla","pariatur","Excepteur","sint","occaecat","cupidatat","non","proident","sunt","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum"]
.map(s => ({ themessage: s}));
// 1. Shuffle the array
shuffle(theobject);
// 2. Add the first 5 elements on the page
for (var i = 0; i < 5; i++) {
$('<div>').addClass("theitem").text(theobject[i].themessage).appendTo($('.container'));
}
// 3. Asynchronous loop to select one of those 5 and replace with next from shuffled array
(function loop(i) {
var j = Math.floor(Math.random() * 5);
$('.container>.theitem').eq(j).animate({ opacity: 0 }).promise().then(function () {
return $(this).text(theobject[i].themessage).animate({ opacity: 1 }).delay(500).promise();
}).then(function () {
loop((i + 1) % theobject.length);
});
})(5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
关于javascript - 随机淡入和淡出屏幕上的 x 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48596775/