随机插入但永远不会彼此相邻

时间:2014-06-01 19:58:55

标签: javascript jquery html random

基于Insert a div in a random location in a list of divs - 我试图将一些猫照片随机插入一张非猫照片:

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

但有没有办法阻止猫依次出现在彼此旁边?它们应该分散开来。

JS:

var insertionTemplate = $('.template').find('.image').html(),
    insertionTargetChildren = $('.main').find('.image'),
    insertionFrequency = 3;

var random;
for (var i = 0; i < insertionFrequency; i++) {
    random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
    insertionTargetChildren.eq(random).append(insertionTemplate);
}

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>

3 个答案:

答案 0 :(得分:1)

在你的循环中你可以检查生成的数字是否等于生成的最后一个数字+ -1

DEMO http://jsfiddle.net/QXdL3/22/

for (var i = 0; i < insertionFrequency; i++) {
    random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;

    if (random != excludeNumA && random != excludeNumB) {
       insertionTargetChildren.eq(random).append(insertionTemplate);
    }
    excludeNumA = random + 1;
    excludeNumB = random - 1;
}

答案 1 :(得分:1)

我已经解决了问题并检查了下一个或上一个元素是否是猫。

var target    = $('.main').find('.image'),
    frequency = 3,
    element   = $();

for (var i = 0; i < frequency; i++) {
    (function getElems() {
        element   = target.eq( Math.floor(Math.random() * target.length) );
        var next  = element.next(),
            prev  = element.prev(),
            all   = element.add(next, prev);

        if (element.hasClass('cat') || next.hasClass('cat') || prev.hasClass('cat')) getElems();
    }());

    var template  = $('.template div').clone(true);
    element.before(template);
}

FIDDLE

答案 2 :(得分:1)

您可以像上面的答案一样对列表进行霰弹,但这样做效率更高,因为您只需要检查插入的精确对象,而不是检查每个图像。

添加2个步骤。第一个应该洗牌图像数组,以便它们每次都处于不同的顺序。第二个应该在另一个列表中创建一个插入点数组。如果您不希望猫图像彼此相邻,请确保插入点列表至少间隔为2.

您还应该为模板使用<script type="text/template">标记。

http://jsfiddle.net/kf2zU/1/

HTML

<script id="cat-template" type="text/template">
    <div class="image">
        <img src="http://placekitten.com/75/150" />
    </div>
</script>
<script id="img-template" type="text/template">
    <div class="image">
        <img src="http://lorempixel.com/75/150" />
    </div>
</script>
<div class="main">
</div>

JS

var catTemplate = $("#cat-template").html();
var imgTemplate = $("#img-template").html();

//place images into .main
var $main = $(".main");
var numImages = 50;
for (var i = 0; i<numImages; i++){
    $main.append($(imgTemplate));
}

//make a list of cat images for example
var numCatImages = 50;
var cats = [];
for (i = 0; i < numCatImages; i++){
    cats.push($(catTemplate));
}

//shuffle the cat list so they appear in random order
cats = _.shuffle(cats);

//create a list of insertion points
var insertionPoints = [];
var insertionIndex = 0;
var minSpacing = 2;
var maxSpacing = 8;
var spacingRange = maxSpacing - minSpacing;
while(insertionIndex < numImages){
    insertionIndex += Math.floor(Math.random() * spacingRange) + minSpacing;
    insertionPoints.push(insertionIndex);
}

//place cat images at the insertion points
//it's important to start from the end and work your way forward so the previous insertions don't mess with subsequent insertion points
//so we reverse the array of insertion points

insertionPoints = insertionPoints.reverse();
var catIndex = 0;
_.each(insertionPoints, function(insertionIndex, i){
    $main.children().eq(insertionIndex).after(cats[catIndex++]);
});