Randomly fade in and out x elements on screen

时间:2018-02-03 11:19:46

标签: javascript jquery

I have an array list of 100 objects that I want to randomly append on to the screen.

                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>')
                }

Ok so my goal is to append five of them at a time on the screen and then randomly replace one by one of those 5 by the next on the "qued list". The one that fades out will be removed from the DOM, also from the object list so it wont get placed again. Any suggestions? Thanks a ton!

1 个答案:

答案 0 :(得分:1)

以下是如何做到这一点:

  • 不是从数组中取一个随机值,而是先根据随机选择对数组进行洗牌。然后你可以迭代那个数组,而不必担心你会得到重复
  • 使用jQuery // foo.cppm module foo; export void test() { } 方法清除并设置5个元素之一的不透明度
  • 使用animate方法创建承诺,并链接在动画准备就绪时执行的promise回调
  • 使用then在选择和淡化下一个项目之前引入一些时间。
  • 将其置于自动调用函数中以使其无限重复
  • 使用delay运算符实现循环数组遍历

代码:

&#13;
&#13;
%
&#13;
// 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);
&#13;
&#13;
&#13;