2011-10-19 225 views
0

我有随机位置的问题。我制作了一个在页面上随机设置<li>的脚本。你可以在这里看到: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(); 

回答

0

我假设你有一组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://stackoverflow.com/questions/7802661 
positionArray.sort(rand); 

init(); 
+0

是啊,这是我寻找的。但脚本中存在一个错误。我不知道它在哪里。最后一个项目得到一个位置。看到这里:http://jsfiddle.net/5L9FN/5/ –

+0

错误是因为你的图片从'1'开始,但数组索引从'0'开始。改变看起来像这样的行:'var imageIndex = parseInt(id.substring(id.length - 1))''var imageIndex = parseInt(id.substring(id.length - 1)) - 1;' – Jamiec

0

把物品按顺序排列的,这样就可以不覆盖已填补的职位,并使用随机洗牌数组中随机顺序。

但是,由于在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/

+0

我怎么能实现该在我的代码? –