javascript - JS,随机高度

标签 javascript html

我希望我的脚本添加 72 个小项目,最后它应该看起来像一个音轨。每个项目的高度应为 30-90px,但每个项目的高度都相同。我找不到我的问题。感谢您的回答。

function frequencyContent() {
    var i = 0;
    while (i < 72) {
        $('.freqInner').append('<div class="frequencyItem"></div>');
        i++;
    };
    $('.frequencyItem').each(function() {
        h = Math.floor(Math.random() * 60) + 30;
        $('.frequencyItem').css("height", h);
    });
};

最佳答案

$('.FrequencyItem') 将选择所有项目并将 css 应用于所有项目,在您的情况下,所有栏都会将高度设置为最后生成的随机数。在 each() 内使用 $(this) 迭代器来引用迭代器中的当前元素。

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element. ( Taken from here )

var i = 0;
while (i < 72) {
  $('.freqInner').append('<div class="frequencyItem"></div>');
  i++;
};
$('.frequencyItem').each(function() {
  var h = Math.floor(Math.random() * 60) + 30;
  $(this).css("height", h);
});
.frequencyItem {
  width: 5px;
  background: red;
  display: inline-block;
  margin-right: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="freqInner"></div>

<小时/>

您甚至可以通过删除 each() 来减少代码。 迭代器,通过使用 css() 添加回调 迭代自身的方法。

var i = 0;
while (i < 72) {
  $('.freqInner').append('<div class="frequencyItem"></div>');
  i++;
};

$('.frequencyItem').css('height', function() {
  return Math.floor(Math.random() * 60) + 30;
});
.frequencyItem {
  width: 5px;
  background: red;
  display: inline-block;
  margin-right: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="freqInner"></div>

<小时/>

或者通过在生成元素时应用 css 来更简单,也 generate element using jQuery .

for (var i = 0; i < 72; i++) {
  $('.freqInner').append($('<div>', {
    class: 'frequencyItem',
    css: {
      height: Math.floor(Math.random() * 60) + 30
    }
  }));
};
.frequencyItem {
  width: 5px;
  background: red;
  display: inline-block;
  margin-right: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="freqInner"></div>

关于javascript - JS,随机高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37418134/

相关文章:

javascript - Chartjs如何从数据库动态更新数据(Chartjs无法获取数据)

javascript - 如何用html标签替换字符串

javascript - 以angularjs形式定义默认值,验证不起作用

html - h1 元素需要 padding-top

javascript - 如果值为 0,如何隐藏 HTML 表格行

javascript - 在没有固定高度/虚拟化的情况下提高长列表的性能

javascript - 时钟在不同时区javascript显示相同时间

html - 当我在 HTML 中将我的 div 标签 float 到另一个 div 中时

javascript - 在本地运行js不断出现此错误

javascript - jquery Quicksand 链接到预过滤页面