【问题标题】:Array value in randomly positioned div随机定位的 div 中的数组值
【发布时间】: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


【解决方案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);

}());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2020-04-29
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多