具有类的对象随机出现/消失在循环上

时间:2016-08-12 07:29:49

标签: jquery animation random

我想模仿明星背景。

在加载时,星星会在整个站点中创建并随机分散。我已经调整了一些代码。

var star="<span class='star'>•</span>";
var numStars=100;
for(var x=1;x<=numStars;x++){
    $(star).appendTo("body");
}
// get window dimentions
var ww = $(window).width();
var wh = $(window).height();
$(".star").each(function(i){
    var posx = Math.round(Math.random() * ww)-20;
    var posy = Math.round(Math.random() * wh)-20;
    $(this).css("top", posy + "px").css("left", posx + "px");
});

https://jsfiddle.net/0quLgtaq/3/

我现在想让它们随机淡入,保持,然后淡出。

我认为这种方法是随机选择一个星星,然后为它添加一个.active类,然后在x秒后删除它。在一个循环上。

我不完全确定从哪里开始。启动我的任何粗略代码都会很棒。感谢

1 个答案:

答案 0 :(得分:2)

您可以使用CSS animations

jQuery(document).ready(function($) {
    var star = "<span class='star'>•</span>";
    var numStars = 100;
    for (var x = 1; x <= numStars; x++) {
        var randomDelay = Math.random()*10;
        $(star)
            .css("animation-delay", randomDelay + "s")
            .appendTo("body");
    }
    // get window dimensions
    var ww = $(window).width();
    var wh = $(window).height();
    $(".star").each(function(i) {
        var posx = Math.round(Math.random() * ww) - 20;
        var posy = Math.round(Math.random() * wh) - 20;
        $(this)
            .css("top", posy + "px")
            .css("left", posx + "px");
    });
});
.star {
    color: black;
    position: absolute;
    opacity: 0;
    animation: fade 2s linear;
}

@keyframes fade {
    0%,
    100% {
        opacity: 0
    }
    50% {
        opacity: 1
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

同样在Fiddle