gpt4 book ai didi

javascript - 随机定位的 div 中的数组值

转载 作者:行者123 更新时间:2023-11-28 07:22:06 25 4
gpt4 key购买 nike

使用这个 - 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();
});
})();

我真正添加的唯一内容是设置数组 varousText = [] 以及填充该数组的 each 函数。

我遇到的问题是我需要迭代数组,因此创建的每个新 div 都使用下一个项目作为其内容,即 div 1 使用数组项目 0,div 2 使用项目 1 等...直到它到达末尾数组,然后再次开始该过程。

最佳答案

我对您的脚本进行了一些修改,以使用递归函数来迭代数组并保持您的延迟和淡入/淡出:

(function() {
//set up the array to hold the random div content
var boastsText = [];
$(".boast ul li").each(function () {
boastsText.push($(this).text());
});


function makeDiv(i){
var divsize = 200;
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);

var $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).fadeOut(500, function() {
$(this).remove();
if (i === boastsText.length) return;
makeDiv(++i);
});
}

//Start the recursion
makeDiv(0);

}());

关于javascript - 随机定位的 div 中的数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30190729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com