2

如果窗口比“x”宽,我会在浏览器加载时加载等高函数。如果我想添加我的功能,我还想在浏览器调整大小为“重新测试”时再次检查“x”。

不知道该怎么做:

// global variables
var compareWidthColumn, //previous width used for comparison
detectorColumn, //the element used to compare changes
smallScreenColumn, // Size of maximum width of single column media query
jQuery(document).ready(function($) {
    //set the initial values
    detectorColumn = jQuery('.js');
    compareWidthColumn = detectorColumn.width();
    smallScreenColumn = '481';

    if ($(window).width() > smallScreenColumn) {
        $('#sidebar_right').equalHeights();
    }    

    jQuery(window).resize(function() {
        //compare everytime the window resize event fires
        if (detectorColumn.width() != compareWidthColumn) {

            //a change has occurred so update the comparison variable
            compareWidthColumn = detector.width();

            if (compareWidthColumn > smallScreenColumn) {
                $('#sidebar_right').equalHeights();
            }
        }

    });
});

整个概念是,如果浏览器宽度超过 481 像素,我只想应用“equalHeights”。这被应用于流体布局,我希望用户调整浏览器的大小,因此调用调整大小。

问题:初始加载工作正常,仅当窗口宽于 481px 时才调用 equalHeight。问题是如果用户从浏览器宽度超过 481 像素开始,然后将其缩小,equalHeight 不会被删除。

我该如何解决?*我尝试学习 jQuery,有点新。

编辑 评论中提到我测量了不同的东西,所以我也尝试了这个:

jQuery(document).ready(function($) {
    //set the initial values
    detectorColumn = jQuery('.js');
    compareWidthColumn = detectorColumn.width();
    smallScreenColumn = '481';

    if ($(window).width() > smallScreenColumn) {
        $('#sidebar_right').equalHeights();
    }    

    jQuery(window).resize(function() {

            if ($(window).width() > smallScreenColumn) {
                $('#sidebar_right').equalHeights();
            }
    });
});

我仍然遇到 equalHeights 没有“重新测量”屏幕调整大小时的元素的问题,如果屏幕小于 480 像素,也不会自行删除。

编辑 2* 我应该提到我使用 2 种不同测量值的原因是在此脚本之前,我声明了一些全局变量:

这是在我的 jquery 页面顶部的脚本上方。

// global variables
var compareWidthColumn, //previous width used for comparison
detectorColumn, //the element used to compare changes
smallScreenColumn, // Size of maximum width of single column media query

我的想法是,如果我在函数之外声明它们将存储这些值。然后当屏幕调整大小时,它将新值与全局值进行比较,如果有变化,重做该功能。

这是不是很糟糕的逻辑?

4

1 回答 1

2

也许我在这里遗漏了一些东西,但下面的简单方法应该可以工作(至少它会做一些事情):

$(function() {
    var $sidebar_right = $('#sidebar_right'),
        smallScreenColumn = 481;
    $(window).on('resize', function() {
        $sidebar_right.height('auto');//remove previously applied equalHeights.
        if($(window).width() > smallScreenColumn) {
            $sidebar_right.equalHeights();
        }
    }).trigger('resize');
});

我假设这是根据此处的评论.height('auto')删除先前应用的正确方法。.equalHeights()

您可能希望重新引入detectorColumn等,但至少从表面上看,这似乎是不必要的并发症。

当文档.equalHeights()中的所有示例均为$(classSelector).equalHeights();. 如果我的理解是正确的,那么类似的东西$('#sidebar_right > div')会更合适(即所有 sidebar_right 的子 div)。

编辑:我的错。通过设置.equalHeights()容器元素,它会自动“循环通过顶级子节点”。请参阅下面@shaWn 评论中的链接。

于 2012-07-15T01:08:58.807 回答