【问题标题】:How add a div inside Another div but in a random position如何在另一个 div 中添加一个 div 但在随机位置
【发布时间】:2012-08-18 21:18:03
【问题描述】:

我正在动态创建 div,并希望将它们添加到父 div 的随机位置而不是最后一个位置,例如

                        var opt = document.createElement("div");
                        var txt = document.createTextNode(str);
                        opt.appendChild(txt);


                        //get the top and left positioning of the elements
                        var x = Math.floor(Math.random() * (400));
                        var y = Math.floor(Math.random() * (50));

                        opt.style.top = y + "px";
                        opt.style.left = x + "px";
                        opt.style.zIndex = zindex;   

                        $("#parentDiv").append(opt);

但问题是 jquery 的 append 函数或 add 函数将 div 放在堆栈的最后位置。我希望它在其他 div 之间随机放置...帮助

【问题讨论】:

  • 您的意思是您最后添加的 div 位于其他 div 之上,还是您的意思是最后添加的 div 被添加到文档的末尾?
  • 尝试添加 opt.style.position="relative";

标签: javascript jquery html random


【解决方案1】:
var $parent = $('#parentDiv');
var $children = $parent.children();             // get possible children
var n = $children.length;                       // there are n children
var pos = Math.floor((n + 1) * Math.random());  // and n+1 insert points

if (n === pos) {
    $parent.append(opt);                        // append after last
} else { 
    $children[pos].before(opt);                 // or insert before
}

编辑我清理了这个以合并 no-children / last child case。

【讨论】:

  • @S.McGrady 但您接受了另一个答案?! [这是不完整的、错误的,并且至少调用了 3 次 $('#parentDiv')$('#parentDiv div') 也违反了 DRY 原则?]
【解决方案2】:

如果已经有div:

var i = Math.round(Math.random() * $('#parentDiv').length);
if (i != $('#parentDiv div').length) $('#parentDiv div').eq(i).before(opt);
else $('#parentDiv div').eq(i - 1).after(opt);

【讨论】:

  • 这仍然无法处理将 first 子元素插入到父元素中。
猜你喜欢
  • 2013-07-11
  • 2020-11-05
  • 2012-07-03
  • 2011-08-07
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
相关资源
最近更新 更多