【发布时间】:2015-05-12 20:37:19
【问题描述】:
使用这个 - random position of divs in javascript 作为起点,我试图随机定位包含数组中文本的 div。
当前代码(主要复制了 Ken Redler 在链接帖子中的答案):
(function makeDiv(){
var divsize = 200;
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
//set up the array to hold the random div content
var boastsText = [];
var i = 0;
$(".boast ul li").each(function() { boastsText.push($(this).text()) });
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'color': color
});
// make position sensitive to size and document's width
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).html(boastsText[i]).appendTo( 'body' ).fadeIn(100).delay(1000).fadeOut(500, function(){
$(this).remove();
makeDiv();
});
})();
我真正添加的唯一内容是设置数组var boastsText = [] 和填充该数组的each 函数。
我遇到的问题是我需要遍历数组,因此创建的每个新 div 都使用下一个项目作为它的内容,即 div 1 使用数组项目 0,div 2 使用项目 1 等等......直到它到达末尾数组,然后再次启动该过程。
【问题讨论】:
-
您有这方面的工作示例吗?你怎么打电话给
makeDiv()? -
你能把
var boastsText = []放在makeDiv()函数之外吗?
标签: javascript jquery arrays