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

时间:2014-04-17 16:38:39

标签: jquery dom equal-heights

我正在使用下面的函数在网格行上设置相等的高度列。在初始页面加载时,该函数在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();
});

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您应该使用:

window.onload = columnConform;

而不是:

<击>

<击>
$(function () {
    columnConform();
});

<击>

这样,图像的大小以及父容器都是相关的。

答案 1 :(得分:0)

您是否尝试过隐藏$( document ).ready( handler )段中的代码而不是onload?

链接 - &gt; HERE