Функция jQuery не запускается при первой загрузке страницы, но срабатывает при обновлении
Я использую функцию ниже, чтобы установить одинаковые высоты столбцов в строках сетки. При начальной загрузке страницы функция устанавливает высоту '0' на div.gallery-item
, При обновлении функция запускается правильно и назначает высоту, как указано в функции.
Вот сценарий:
/* 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();
});
Любой совет?
2 ответа
Вы должны использовать:
window.onload = columnConform;
вместо:
$(function () {
columnConform();
});
Таким образом, размер изображений и, следовательно, родительский контейнер, будут актуальны.
Вы пытались спрятать свой код в $( document ).ready( handler )
сегмент, а не нагрузка?
Ссылка -> ЗДЕСЬ