简体   繁体   English

将div插入div容器内的随机位置

[英]Insert div into random location inside a container of divs

How do I insert a div into a random location inside a container of divs? 如何将div插入div容器内的随机位置? Similar to Insert a div in a random location in a list of divs except I'm not using a list. 类似于将div插入div列表中的随机位置,除了我不使用列表。

Right now it appears inside a random container div, not randomly inside the container itself: 现在,它出现在随机容器div中,而不是随机出现在容器本身中:

http://jsfiddle.net/frank_o/QXdL3/15/ http://jsfiddle.net/frank_o/QXdL3/15/

HTML: HTML:

<div class="template" style="display: none;">
  <div class="image">
    <img src="http://placekitten.com/75/150">
  </div>
</div>
<div class="main">
  <div class="image">
    <img src="http://lorempixel.com/75/150">
  </div>
  <div class="image">
    <img src="http://lorempixel.com/75/150">
  </div>
  <div class="image">
    <img src="http://lorempixel.com/75/150">
  </div>
</div>

JS: JS:

var template = $('.template').find('.image').clone(),
  target = $('.main'),
  targetChildren = target.find('.image'),
  random = Math.floor(Math.random() * targetChildren.length);

targetChildren.eq(random).append(template);

You're almost there. 你快到了。 You just need to change append to after ; 你只需要改变appendafter ; change: 更改:

insertionTargetChildren.eq(random).append(insertionTemplate);

To: 至:

insertionTargetChildren.eq(random).after(insertionTemplate);

Your current code inserts the new div into another div as follows: 您当前的代码将新的div插入另一个div中,如下所示:

<div class="image" style="position: absolute; left: 150px; top: 310px;">
    <img src="http://lorempixel.com/75/150">
  <div class="image" style="position: absolute; left: 225px; top: 310px;">
    <img src="http://placekitten.com/75/150">
  </div>
</div>

The new version will produce the following: 新版本将产生以下内容:

<div class="image" style="position: absolute; left: 150px; top: 310px;">
    <img src="http://lorempixel.com/75/150">
</div>
<div class="image" style="position: absolute; left: 225px; top: 310px;">
  <img src="http://placekitten.com/75/150">
</div>

This will put it in random position: 这会将其置于随机位置:

random = Math.floor(Math.random() * (targetChildren.length+1));
if(random > targetChildren.length){
   target.append(template);
}else{
    targetChildren.eq(random).before(template);
}

The targetChildren.length+1 is to add the possibility of appending in the last place ;) targetChildren.length+1是要添加最后添加的可能性;)

You were very close! 你很亲密!

Instead of .clone() , try using .html() like my example below. 像下面的示例一样,尝试使用.html()代替.clone()

Also, I slightly changed your loop along with the random number generator. 另外,我与随机数生成器一起略微更改了您的循环。

Works very well now. 现在效果很好。 Refresh the page to see three random kitty photos added somewhere within the other images. 刷新页面以查看在其他图像中的某处添加的三张随机小猫照片。

WORKING EXAMPLE 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM