我试图让 div 从上到下下降。 这是我尝试过的代码,但它不能满足我的需求。我想在准备好后生成 20 div,然后如何使 20 div 从上到下连续下降。有没有可能在 jquery 中做到这一点。 http://jsfiddle.net/MzVFA/ 这是代码
function fallingSnow() {
var snowflake = $('<div class="snowflakes"></div>');
$('#snowZone').prepend(snowflake);
snowX = Math.floor(Math.random() * $('#site').width());
snowSpd = Math.floor(Math.random() + 5000);
snowflake.css({'left':snowX+'px'});
snowflake.animate({
top: "500px",
opacity : "0",
}, snowSpd, function(){
$(this).remove();
fallingSnow();
});
}
var timer = Math.floor(Math.random() +1000);
window.setInterval(function(){
fallingSnow();
}, timer);
非常感谢您的帮助。
谢谢
最佳答案
不确定这是否是您想要的。
我正在制作 20 个雪花的动画,等到动画完成所有雪花,然后重新开始。
function fallingSnow() {
var $snowflakes = $(), qt = 20;
for (var i = 0; i < qt; ++i) {
var $snowflake = $('<div class="snowflakes"></div>');
$snowflake.css({
'left': (Math.random() * $('#site').width()) + 'px',
'top': (- Math.random() * $('#site').height()) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake);
}
$('#snowZone').prepend($snowflakes);
$snowflakes.animate({
top: "500px",
opacity : "0",
}, Math.random() + 5000, function(){
$(this).remove();
// run again when all 20 snowflakes hit the floor
if (--qt < 1) {
fallingSnow();
}
});
}
fallingSnow();
更新
此版本只创建 20 个 div 一次,并一次又一次地为它们制作动画。
function fallingSnow() {
var $snowflakes = $(),
createSnowflakes = function () {
var qt = 20;
for (var i = 0; i < qt; ++i) {
var $snowflake = $('<div class="snowflakes"></div>');
$snowflake.css({
'left': (Math.random() * $('#site').width()) + 'px',
'top': (- Math.random() * $('#site').height()) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake);
}
$('#snowZone').prepend($snowflakes);
},
runSnowStorm = function() {
$snowflakes.each(function() {
var singleAnimation = function($flake) {
$flake.animate({
top: "500px",
opacity : "0",
}, Math.random() + 5000, function(){
// this particular snow flake has finished, restart again
$flake.css({
'top': (- Math.random() * $('#site').height()) + 'px',
'opacity': 1
});
singleAnimation($flake);
});
};
singleAnimation($(this));
});
};
createSnowflakes();
runSnowStorm();
}
fallingSnow();
更新2
一旦为每个雪花完成动画,这个初始化 left
的动画在我看来看起来更自然。
还更改了延迟从
Math.random() + 5000
到
Math.random()*-2500 + 5000
关于javascript - 在 Jquery 中创建随机下落对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19333422/