2011-10-19 208 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

我怎麼能實現該在我的代碼? –