JS,随机高度



我希望我的脚本添加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)来引用迭代器中的当前元素。

.each()方法旨在使DOM循环结构简洁且不易出错。当被调用时,它会遍历作为jQuery对象一部分的DOM元素。每次运行回调时,都会从0开始传递当前循环迭代。更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字this引用该元素。(取自此处)

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,也可以使用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>

您每次都在调整类,这会统一地更改该类中的每个元素。。。尝试使用$(this)调整每个单独的元素,如下所示:

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;
$(this).css("height", h);
});
};

这与其他人所说的基本相同,但我的版本2更高效,因为它在第一个循环中一次性完成。

请注意,您有一个带有h变量的acidental全局

function frequencyContent() {
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);
});
};

简单的单程版

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

最新更新