我希望我的脚本添加 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/