2011-10-16 37 views
1

我試圖實現Pinterest的牆,如下所述:how to replicate pinterest.com's absolute div stacking layout雙師型「每個」循環來找到最小的值在Array

無論如何,我被困在一個點,我需要找到指數Array的最小值,但在同一時間,當前塊的高度添加到該值(這樣最小的值並不總是相同的)。

var grid = new Array(4); // 4 as example 

// Add values to the Array 
$.each(grid, function(j) { 
    grid[j] = j; 
}); 
var smallest_index = 0; 
var smallest_value = grid[0]; 

// Find the index of the smallest value in the Array 
SmallestValueIndex = function() { 
    $.each(grid, function(i, v) { 
     if (v < smallest_value) { 
      smallest_index = i; 
      smallest_value = v; 
     } 
    }); 
} 

// Go through all my '<div>' and add the height to the current smallest value 
$.each(blocs, function() { 
    SmallestValueIndex(); 
    var h = $(this).height(); 
    grid[smallest_index] += h; 
}); 

每一次,最小值應該是不同的,因爲我加的高度的以前最小值(所以它不是最小的值了)。

但在我的測試中,它仍然是一樣的。

回答

2

試試看看這個代碼。它採用原生Math.min功能,而不是一個低效的jQuery循環:

$.each(blocs, function() { 
    var lowest = Math.min.apply(null, grid); 
    var index = grid.indexOf(lowest); 
    grid[index] += $(this).height(); 
} 

首先,Math.min()得到最低數出所有網格元素。然後,grid.indexOf()用於查找此元素的位置。最後,將高度添加到索引爲index的網格中的元素。

+0

謝謝。這正是我尋找的功能。但是,我擔心,無法訪問該值的_index_,但你告訴了我該怎麼做。 一個問題:'null'在apply()函數中做了什麼? – jgthms

+0

'.apply'接受兩個參數:被調用函數的'this'關鍵字將被設置爲第一個參數,並且參數列表通過第二個參數被指定。在這種情況下,'this'關鍵字是不相關的,可以設置爲任何內容。另請參閱:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply –

+0

請記住,舊版本的IE沒有Array.indexOf(),因此您必須填充該方法如果你想在所有瀏覽器中使用它。 – jfriend00