【问题标题】:Array with random positions具有随机位置的数组
【发布时间】:2025-11-25 12:50:02
【问题描述】:

我对随机位置有疑问。我制作了一个在页面上设置<li> random 的脚本。你可以在这里看到它:Click here

但问题是。项目重叠。我想用一个数组制作这个脚本。我想要一个位置固定的数组。总是有 8 个项目。而这八项,都有一个固定的位置。

我怎样才能做到这一点?如何制作具有固定位置的数组?

这是我的代码:

var images = [];

function init() {
    $('.friend-selection li > div').each(function(){

        var id = this.id;
        var img = $('#img_' + id);
        var randomTop = 400*Math.random(); //random top position
        var randomLeft = 500*Math.random()+1; //random left position

        $("#parent_" + id).css({ //apply the position to parent divs
            top     : randomTop,
            left    : randomLeft
        });
    });
};

init(); 

【问题讨论】:

    标签: javascript jquery random html-lists


    【解决方案1】:

    我假设您有一组 8 个固定的、不重叠的位置,您想随机且唯一地使用它们:

    var images = [];
    
    // Constructor for the "Position" structure
    function Position(left, top) {
        this.left=left;
        this.top=top;
    }
    
    // sortFunction routine to help randomize array
    function rand(ar){
        return 0.5-Math.random();
    }
    
    // Array containing the 8 positions you want to use
    var positionArray = [
          new Position(0,  0) 
        , new Position(50, 50) 
        , new Position(100,100) 
        , new Position(150,150) 
        , new Position(200,200) 
        , new Position(250,250) 
        , new Position(300,300) 
        , new Position(350,350) 
    ];
    
    function init() {
        $('.friend-selection li > div').each(function(){
    
            var id = this.id;
            var img = $('#img_' + id);
            var imageIndex = parseInt(id.substring(id.length - 1)); // This is a hack because you're using "picture*" as the id
    
            $("#parent_" + id).css({ //apply the position to parent divs
                top     : positionArray[imageIndex].top,
                left    : positionArray[imageIndex].left
            });
        });
    };
    
    
    // Randomize array - http://*.com/questions/7802661
    positionArray.sort(rand);
    
    init(); 
    

    【讨论】:

    • 是的,这就是我要找的。但是脚本中有一个错误。我不知道它在哪里。最后一项得到nog一个位置。见这里:jsfiddle.net/5L9FN/5
    • 这个bug是因为你的图片从1开始,但是数组索引从0开始。将如下所示的行:var imageIndex = parseInt(id.substring(id.length - 1)) 更改为 var imageIndex = parseInt(id.substring(id.length - 1))-1;
    【解决方案2】:

    将项目按顺序排列在数组中,这样就不会覆盖已经填充的位置,并使用 Shuffle 以随机顺序对数组进行洗牌。

    但由于 Javascript 中没有这样的功能,您将自己编写一个。这样的事情会奏效。

    shuffle = function(o){
        for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o;
    };
    
    
    alert(shuffle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
    

    http://jsfiddle.net/uxnn7/

    【讨论】: