jQuery函数在第一页加载时不触发,但在刷新时会触发fine

jQuery Function not triggering on first page load, but triggering fine on refresh

本文关键字:刷新 fine 函数 第一页 加载 jQuery      更新时间:2023-09-26

我使用下面的函数在网格行上设置等高列。在初始页面加载时,函数将div.gallery-item上的高度设置为"0"。刷新时,函数会正确启动,并按照函数中的规定指定高度。

这是脚本:

/* 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();
});

有什么建议吗?

您应该使用:

window.onload = columnConform;

而不是:

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

通过这种方式,图像的大小以及父容器都是相关的。

您是否尝试将代码隐藏在$( document ).ready( handler )段中而不是加载?

有关.ready()的更多信息,请访问jQuery文档页面。