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;
});
每一次,最小值應該是不同的,因爲我加的高度的以前最小值(所以它不是最小的值了)。
但在我的測試中,它仍然是一樣的。
謝謝。這正是我尋找的功能。但是,我擔心,無法訪問該值的_index_,但你告訴了我該怎麼做。 一個問題:'null'在apply()函數中做了什麼? – jgthms
'.apply'接受兩個參數:被調用函數的'this'關鍵字將被設置爲第一個參數,並且參數列表通過第二個參數被指定。在這種情況下,'this'關鍵字是不相關的,可以設置爲任何內容。另請參閱:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply –
請記住,舊版本的IE沒有Array.indexOf(),因此您必須填充該方法如果你想在所有瀏覽器中使用它。 – jfriend00