jQuery 调整大小代码导致 IE7 中的永久调整大小事件

jQuery resizing code causing perpetual resize event in IE7

这是我写的 JavaScript (jQuery) 的一点,将元素缩小到尽可能高,同时仍将整个页面保持在首屏。它的工作方式本质上是 "calculate the height difference between the document and the window, and make the element smaller by that much"。 (见下文。)

据我所知,这工作得很好——不幸的是我仍然需要 IE7 支持,而且该浏览器中的行为有点不稳定。具体来说,调用我的函数似乎会触发另一个调整大小事件,导致一种反馈循环。

IE7 显然是唯一发生这种情况的浏览器,我还没有弄清楚为什么会发生这种情况。我已经尝试将目标高度调小以确保没有超出范围,但结果是一样的。

让我的代码不触发 IE7 中的调整大小事件的最佳方法是什么?

function stretchToBottom($element) {

    (window.onresize = function () {

        // temporarily reset the element's height so $(document).height() yields the right value
        $element.css({maxHeight: ''});

        var heightDiff = $(document).height() - $(window).height();
        if (heightDiff <= 0) {
            return;
        }

        var initialHeight = $element[0].scrollHeight;
        var minHeight = 200;
        var targetHeight = initialHeight - heightDiff;
        var height = Math.max(targetHeight, minHeight);

        $element.css({maxHeight: height + 'px'});

    })();

}

用以下代码包装您的代码:

<!--[if !IE7]>-->
//NONE IE code comes here
<!--<![endif]-->

<!--[if IE7]>
//ONLY IE7 code comes here
<![endif]-->

more info here

我刚刚发现 this question 它描述了我遇到的完全相同的问题。前两个答案提供了一个可行的解决方案:存储当前 window 维度并仅在它们实际更改时才处理事件侦听器。

作为记录,这是我目前拥有的工作代码。我将函数名称更改为更准确,并将 "add event listener" 部分移至函数外部。

function shrinkToFit($element) {

    $element.css({maxHeight: ''});

    var heightDiff = $(document).height() - $(window).height();
    if (heightDiff <= 0) {
        return;
    }

    var initialHeight = $element[0].scrollHeight;
    var minHeight = 200;
    var targetHeight = initialHeight - heightDiff;
    var height = Math.max(targetHeight, minHeight);

    $element.css({maxHeight: height + 'px'});

}
var lastWindowWidth = $(window).width();
var lastWindowHeight = $(window).height();
$(window).on('resize', function () {
    if (lastWindowWidth !== $(window).width() || lastWindowHeight !== $(window).height()) {
        shrinkToFit($tableContainer);
        lastWindowWidth = $(window).width();
        lastWindowHeight = $(window).height();
    }
});