0

我正在尝试将图像放置在网页上的横幅 div 中。图像需要沿 x 轴“随机”定位(使用 CSSleft属性),因此在加载页面时它们并不总是相同的。我有以下脚本来执行此操作(它还设置了随机延迟,因此图像每次都以不同的时间顺序出现:

for (var i = 1; i <= 5; i++) {

    var delay = Math.floor(Math.random() * 800) + 1;
    var xPos = Math.floor(Math.random() * 900) + 1;

    $('#item'+i).css('left',xPos+'px').delay(delay).animate({ top: 18 }, { duration: 1000, easing: 'easeOutBounce' });

}

但是,问题在于图像之间经常有太多重叠,并且它们彼此隐藏在一起。所以我想歪曲随机性,以便所有 xPos 变量之间至少有 100px 的差异。这应该给我一个随机的外观,但也让项目大部分可见。

必须有一个词来描述这种事情,但经过搜索,我找不到任何有用的东西来说明如何实现它。

谁能在这里指出我正确的方向?

非常感谢。

编辑:

好的,所以尝试滚动我自己的功能来做到这一点。我想我快到了。我正在做的是创建一个初始随机数并将其添加到一个数组中,然后遍历 5 个项目中的每一个并生成另一个随机数,然后比较它以确保它与当前数组中的任何东西有 100 多个不同。

代码是这样的(目前并非我的所有变量都在使用 - 这是一项正在进行的工作!):

function randomImagePlacement() {
    var containerWidth = 940;                   // Width of container element
    var itemWidth = 267;                        // Width of item (taking into account rotation)
    var minX = 0;                               // Minimum left position of an item
    var maxX = containerWidth - itemWidth;      // Maximum left position of an item
    var minSeparation = 100;                    // Minimum number of pixels of separation between items
    var numberOfItems = 5;                      // Total number of items
    var randomNumbers = [];                     // Array 'container' to hold random numbers

    for (var i = 1; i <= numberOfItems; i++) {

        if (i == 1) {
            var firstRandomNumber = Math.floor(Math.random() * 700) + 1;
                    randomNumbers.push(firstRandomNumber);
                    console.log('First random number: ' + firstRandomNumber);
        } else {
                    var newRandomNumber = Math.floor(Math.random() * 700) + 1;

            /*
            This if/else block works okay but it doesn't keep checking differences until the criteria is met
            if (checkDiff(newRandomNumber, randomNumbers)) {
                        console.log('New number (' + newRandomNumber + ') sufficiently different enough');
                        randomNumbers.push(newRandomNumber);
            } else {
                        console.log('New number (' + newRandomNumber + ') NOT sufficiently different enough');
            }
            */
            /* This do/while block is my attempt at trying to run the check diff function until the criteria is met, but it just results in the browser crashing */     
            do {
                        randomNumbers.push(newRandomNumber);
            } while (checkDiff(newRandomNumber, randomNumbers) == true);

        }

    }

    for (var i = 0; i < randomNumbers.length; i++) {
        console.log('From final array: ' + randomNumbers[i]);
    }

}


function checkDiff(newRandomNumber, currentArray) {
    console.log('newRandomNumber = ' + newRandomNumber);

    var proximityMatch = false;
    for (var i = 0; i < currentArray.length; i++) {
        console.log('Diff between ' + currentArray[i] + ' and ' + newRandomNumber + ' = ' + Math.abs(currentArray[i] - newRandomNumber));
        if (Math.abs(currentArray[i] - newRandomNumber) > 100) {
            proximityMatch = true;
        }
    }
    if (proximityMatch == true) {
        return true;
    } else {
        return false;
    }
}

randomImagePlacement();

基本上它失败的地方是在上面的 do/while 循环中。我不确定执行此类操作的正确方法,但我基本上需要说“继续运行 checkDiff 函数,直到它返回 true;当它返回 true 时,将 newRandomNumber 添加到数组中;如果它不返回再次运行它”。

谁能帮我解决这个问题?

非常感谢!

4

2 回答 2

0

您可以解决此问题的一种可能方法是:

item0.x = //随机数

item1.x = item0.x+item0.width + 100 + (随机数)

item2.x = item1.x+item1.width + 100 +(随机数)

等等

于 2013-01-28T17:34:31.957 回答
0

更新

抱歉,我没有意识到您需要对所有生成的值进行比较。这将起作用:

var isLessThanMinSeparation = function checkDiff(randomNumber, randomNumbers, minSeparation) {
    var lessThan100 = false,                // Flag for whether minSeparation has been maintained
        i = 0;                              // Incrementer
    console.log('randomNumber = ' + randomNumber);
    for (i = 0; i < randomNumbers.length; i += 1) {
        console.log('Diff between ' + randomNumbers[i] + ' and ' + randomNumber + ' = ' + Math.abs(randomNumbers[i] - randomNumber));
        lessThan100 = lessThan100 || Math.abs(randomNumbers[i] - randomNumber) <= minSeparation;
    }
    return lessThan100;
};
var randomImagePlacement = function randomImagePlacement(numberOfItems, minSeparation) {
    //numberOfItems = 5,                    // Total number of items
    //minSeparation = 100,                  // Minimum number of pixels of separation between items
    var randomNumbers = [],                 // Array 'container' to hold random numbers
        randomNumber = 0,                   // Random number
        i = 0;                              // Incrementer
    for (i = 1; i <= numberOfItems; i += 1) {
        while (isLessThanMinSeparation(randomNumber, randomNumbers, minSeparation)) {
            randomNumber = Math.floor(Math.random() * 700) + 1;
        }
        randomNumbers.push(randomNumber);
    }
    return randomNumbers;
};
console.log(randomImagePlacement(5, 100));

我要做到这一点的方式是:

  1. 存储最后一个随机分配的位置
  2. 使用循环(最少运行一次)分配新的随机分配位置
  3. 比较新随机分配的位置,如果差值 < 100,则重新进入循环

一个例子:

var randomizeImgPlacement = function randomizeImgPlacement() {
    var i = 0,
        delay = 0,
        xPos = 0,
        lastPos = 1000; //Default to 1000 so very first assignment has at least 100 difference
    for (i = 1; i <= 5; i += 1) {
        delay = Math.floor(Math.random() * 800) + 1;
        do { //loop assignment of xPos
            xPos = Math.floor(Math.random() * 900) + 1;
        } while (Math.abs(xPos) - Math.abs(lastPos) >= 100); // while difference is < 100
        $('#item' + i).css('left', xPos + 'px').delay(delay).animate({
            top: 18
        }, {
            duration: 1000,
            easing: 'easeOutBounce'
        });
        lastPos = xPos; //store lastPos for loop comparison
    }
};
于 2013-01-28T17:48:47.230 回答