【发布时间】:2017-05-04 15:45:24
【问题描述】:
$(function(){
var howManyParticles = 11;
var bodyWidth = $(document).width();
var randomSpawn = Math.floor(Math.random() * bodyWidth) + 1;
var particleStyle = "background: lightgray;width: 10px;height: 10px;min-height: 10px;min-width: 10px;position: fixed;bottom: 0;left:" + randomSpawn + ";";
var particle = $("<div class='particle' style='"+ particleStyle +"'> </div>");
function spawnParticles(){
for(var i = 0; i <= howManyParticles; i++)
{
$('body').append(particle);
console.log('spawned');
}
}
spawnParticles();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这只会在窗口中生成 1 个项目,我如何让它生成与 i <= howManyParticles 一样多的项目?
编辑:我的最终代码
我忘记了我需要将math.random 函数放在循环中,以便为生成的每个不同粒子赋予不同的水平值!
$(function(){
var howManyParticles = 11;
var bodyWidth = $(document).width();
function spawnParticles(){
for(var i = 0; i <= howManyParticles; i++)
{
var randomSpawn = Math.floor(Math.random() * bodyWidth) + 1;
var particleStyle = "background: lightgray;width: 10px;height: 10px;min-height: 10px;min-width: 10px;position: fixed;bottom: 0;left:" + randomSpawn + ";";
var particle = $("<div class='particle' style='"+ particleStyle +"'> </div>");
$('body').append(particle);
}
}
spawnParticles();
});
【问题讨论】:
标签: javascript jquery append