javascript - 如何使用 jquery 使我的 div 在两侧 400 px 内生成?

标签 javascript jquery html

我正在为网页制作一个动画背景,它会生成看起来像气泡的 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/

相关文章:

javascript - td 元素上的 OnClick 函数返回第一列值和标题值

javascript - 使用 new 运算符调用函数不返回值?

php - 从 javascript 添加标签

php - 如何根据 php 数据库值动态更改 HTML 中的内容?

python - 通过 Python 中的 Selenium 选择按钮登录

javascript - Popup Modal 的动态填充

javascript - 无法在 aptana studio 中运行 "canvas"标记和 javascript 程序

javascript - 添加新元素后不触发事件

javascript - 如何扩展文本区域以垂直和水平适应文本?

javascript - 为什么 background-size 或 background-repeat 属性不适用于我的图像 slider ?