2014-04-17 38 views
0

我正在使用下面的函數在網格行上設置相等高度的列。在初始頁面加載時,該函數在div.gallery-item上設置高度「0」。在刷新時,該功能正確踢入,並按照功能中的規定分配高度。jQuery函數沒有在第一頁加載時觸發,但在刷新時觸發很好

這裏的腳本:

/* Responsive equal height columns for gallery (http://css-tricks.com/examples/EqualHeightsInRows/) */ 

var currentTallest = 0, 
currentRowStart = 0, 
rowDivs = new Array(); 

function setConformingHeight(el, newHeight) { 
// set the height to something new, but remember the original height in case things  change 
el.data("originalHeight", (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight"))); 
el.height(newHeight); 
} 

function getOriginalHeight(el) { 
// if the height has changed, send the originalHeight 
return (el.data("originalHeight") == undefined) ? (el.height()) : (el.data("originalHeight")); 
} 

function columnConform() { 

// find the tallest DIV in the row, and set the heights of all of the DIVs to match it. 
$('div.gallery-item').each(function() { 

    // "caching" 
    var $el = $(this); 

    var topPosition = $el.position().top; 

    if (currentRowStart != topPosition) { 

     // we just came to a new row. Set all the heights on the completed row 
     for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest); 

     // set the variables for the new row 
     rowDivs.length = 0; // empty the array 
     currentRowStart = topPosition; 
     currentTallest = getOriginalHeight($el); 
     rowDivs.push($el); 

    } else { 

     // another div on the current row. Add it to the list and check if it's taller 
     rowDivs.push($el); 
     currentTallest = (currentTallest < getOriginalHeight($el)) ? (getOriginalHeight($el)) : (currentTallest); 

    } 
    // do the last row 
    for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) setConformingHeight(rowDivs[currentDiv], currentTallest); 

}); 

} 


$(window).resize(function() { 
columnConform(); 
}); 

$(function() { 
columnConform(); 
}); 

我知道這是值得做的,我怎麼加載功能。關於我從這個腳本中得到的文章的建議是使用window.onload,如果圖像是在列上設置不同的高度,但我已經嘗試將其添加到腳本的最後部分,如下所示,並且函數不會'完全觸發。

$(window).onload = (function() { 
columnConform(); 
}); 

有什麼建議嗎?

+0

嘗試$(document).ready() – Ruben

回答

1

,您應該使用:的

window.onload = columnConform;

代替:

$(function() { 
    columnConform(); 
}); 

這樣,圖像的大小,以及父容器,將是相關的。

+0

我已經給出了這一點,它可以工作,但是在加載時沒有相同高度的列的內容會出現閃現。有沒有辦法在腳本完成它的事情後才顯示內容?我使用'$(function(){ \t window.onload = columnConform; });' – jasonbradberry

+1

Ya,默認情況下隱藏它,顯示一次onload處理程序被調用。編輯:但不要嵌套它準備處理程序,這是無用的('$(function(){...});'是準備處理程序的簡寫!所以我的意思是,只需使用'window.onload = columnConform;'。僅供參考,爲避免閃光,通常網站使用某種加載動畫,您必須按照您自己的邏輯實施它。 –

+0

謝謝。我假設你可以通過設置'display:none;'來爲每個div默認設置,然後在'columnConform;'函數中添加'display:block'和高度? – jasonbradberry

0

您是否試過在$(document).ready(handler)分段中存儲代碼而非onload?

連接 - >HERE

相關問題