我正在为网页制作动画背景,使div元素看起来像气泡并为其设置动画效果。我希望气泡仅在屏幕的左侧400px和右侧400px内产生。我可以让它们在中间生成,但是当我尝试使其在边缘生成时,会破坏代码。(也许是无限循环?)
function bubble() {
var rightOffset = $(window).width() - 400; //where i want them on the right
do {
var leftPx = Math.floor(Math.random() * $(window).width() - 100);
} while (leftPx >= 400 || rightOffset <= leftPx);
var topPx = Math.floor(Math.random() * $(window).height() - 100); //not even going to worry about the top yet
if(bubbleCount <= 30){
bubbleCount ++;
$('html').append("<div class=bubble style=' left: " + leftPx + "px; top: " + topPx + "px;'></div>");
$('.bubble').animate({
opacity: 0.5,
}, 3000, 'swing')
.animate({
opacity: 0,
}, 3000, 'swing', function(){
$(this).remove();
bubbleCount -= 1;
});
}
}
为什么不简单地随机分配一侧呢?这样,您不必检查并丢弃潜在的头寸。这样的事情。
function randomBetween(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
var width = $(window).width();
var leftPixels = Math.round(Math.random()) ? randomBetween(0, 400) :
randomBetween(width - 400, width);
此处发生的情况是,它首先随机生成0或1,然后如果它是1,则生成LEFT边值,如果0则生成RIGHT边值。没有多余的迭代会使您的程序变慢。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句