【问题标题】:Check Resize Only On Completion检查仅在完成时调整大小
【发布时间】:2012-11-30 10:40:06
【问题描述】:

在开发具有非常具体设计细节的导航菜单时,我使用它来检查窗口大小并在选定元素后附加一些代码。

$(document).ready(function() {
// Optimalisation: Store the references outside the event handler:
var $window = $(window);

function checkWidth() {
    var windowsize = $window.width();
    if (windowsize >= 768) {
        //if the window is greater than 440px wide then turn on jScrollPane..
        $('nav.dropdowns ul.patient>li:nth-child(4n+5)').after('<div class="clear"></div>');
    }
    else if (windowsize <= 767) {
        //if the window is greater than 440px wide then turn on jScrollPane..
        $('nav.dropdowns ul.patient>li:nth-child(3n+4)').after('<div class="clear"></div>');
    }
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});

问题是它一直在触发,这会无休止地附加我的代码。我可以通过删除事件监听器轻松解决这个问题。这很好用,因为它的最终大小加载了一个窗口。但就流体响应而言,它作为事件仅在加载时失败,之后的任何时候都失败。我查看了其他一千个脚本,但没有找到阻止事件一次又一次触发的方法,而我实际上可以开始工作。

【问题讨论】:

  • 您是否尝试过使用 CSS 媒体查询来完成此任务?响应式设计通常发生在那里。
  • 我要指出我们支持 IE7/8,因此需要 jQuery 来代替 CSS 选择器......但我刚刚找到 Selectivizr.js
  • 我不知道有多少移动设备正在使用 IE7/8。您确定需要它来响应吗?

标签: jquery events listener responsive-design


【解决方案1】:

如果您只想不过度触发该功能,您可以使用setTimeout 和clearTimeout。试试这样的:

$(document).ready(function() {
    // Optimalisation: Store the references outside the event handler:
    var $window = $(window);

    function checkWidth() {
        var windowsize = $window.width();
        if (windowsize >= 768) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $('nav.dropdowns ul.patient>li:nth-child(4n+5)').after('<div class="clear"></div>');
        }
        else if (windowsize <= 767) {
            //if the window is greater than 440px wide then turn on jScrollPane..
            $('nav.dropdowns ul.patient>li:nth-child(3n+4)').after('<div class="clear"></div>');
        }
    }

    var timeoutId;
    function resizeEvent(){
        // 'reset' the timeout each fire
        clearTimeout(timeoutId);
        // save reference to the timeout delay in 'timeoutId'.  10ms delay
        timeoutId = setTimeout(checkWidth, 10);
    }

    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(resizeEvent);
});

这将不断触发resizeEvent(),但10ms 的延迟将阻止checkWidth() 不断运行。

注意:这是您的问题的解决方案,但可能不是最佳解决方案。您应该在CSS 中尽可能多地实现目标

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2013-09-19
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多