我正在为网页制作一个动画背景,它会生成看起来像气泡的 div 元素并为其透明度设置动画。我希望气泡仅在屏幕左侧 400 像素和右侧 400 像素内生成。我可以让它们在中间生成,但是当我尝试让它在边缘生成时,它会破坏代码。 (也许是无限循环?)
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,则生成左侧值,如果是 0,则生成右侧值。没有额外的迭代会减慢您的程序。
关于javascript - 如何使用 jquery 使我的 div 在两侧 400 px 内生成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36771320/