簡體   English   中英

將div插入div容器內的隨機位置

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

如何將div插入div容器內的隨機位置? 類似於將div插入div列表中的隨機位置,除了我不使用列表。

現在,它出現在隨機容器div中,而不是隨機出現在容器本身中:

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

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:

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

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

你快到了。 你只需要改變appendafter ; 更改:

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

至:

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

您當前的代碼將新的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>

新版本將產生以下內容:

<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>

這會將其置於隨機位置:

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

targetChildren.length+1是要添加最后添加的可能性;)

你很親密!

像下面的示例一樣,嘗試使用.html()代替.clone()

另外,我與隨機數生成器一起略微更改了您的循環。

現在效果很好。 刷新頁面以查看在其他圖像中的某處添加的三張隨機小貓照片。

工作實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM