javascript - 在 JQuery Resize 上触发多个事件

标签 javascript jquery event-handling

我一直在使用下面的 JQuery 代码来处理 Drupal 站点上菜单的一些响应能力。在调整大小函数中的两行注释中,我本质上是尝试根据屏幕尺寸启用和禁用相反的事件。我的第一个问题是,由于此处理程序触发将在调整大小函数中进行,尝试这样的操作是否会导致任何类型的重大性能损失?我的第二个问题是如何?我一直在尝试使用 on 和 off 函数来根据需要启用/禁用这些处理程序,但我认为整体语法不正确。我认为最好将现有的事件处理程序分解为函数,但将它们保留为代码示例。

jQuery(document).ready(function($) {
  $('.nav-toggle').click(function() {
   $('#main-menu div ul:first-child').slideToggle(250);
   return false;
});

if( ($(window).width() > 600) || ($(document).width() > 600) ) {
  $('#main-menu li').mouseenter(function() {
    $(this).children('ul').css('display', 'none').stop(true, 
    true).slideToggle(1).css('display', 
    'block').children('ul').css('display', 'none');
  });

  $('#main-menu li').mouseleave(function() {
    $(this).children('ul').stop(true, true).fadeOut(1).css('display', 'block');
  })
    } 

else {
$('.drop-down-toggle').click(function() {
  $(this).parent().children('ul').slideToggle(500);
});
}

 $(window).resize(function() {
 if($(window).width() > 600) {
    $('div.menu-navigation-container ul.menu').css('display','block');
    $('div.menu-navigation-container ul.menu ul.menu').hide();
    //**Disable dropdown click and enable mouse enter and mouse leave**
 }
 else{
    $('div.menu-navigation-container ul.menu').hide();
    //**Disable mouse enter and mouse leave but enable dropdown click**
 }
});

});

最佳答案

使用节流功能

function throttle (callback, limit) {
    var wait = false;                 // Initially, we're not waiting
    return function () {              // We return a throttled function
        if (!wait) {                  // If we're not waiting
            callback.call();          // Execute users function
            wait = true;              // Prevent future invocations
            setTimeout(function () {  // After a period of time
                wait = false;         // And allow future invocations
            }, limit);
        }
    }
}

$(window).on('resize', throttle(yourResizeFunction, 200))

在此处阅读原因:http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

关于javascript - 在 JQuery Resize 上触发多个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989925/

相关文章:

javascript - 通过 jQuery 在 chrome 扩展内容脚本中访问跨源 iframe 的 HTML?

javascript - 无法实现自动注销 react 本地存储

jQuery - 选择器

javascript - 没有 jquery 无法正确加载外部脚本

c# - 如何取消 Hook C# 中的事件处理程序

javascript - discord.js 未处理的PromiseRejectionWarning : TypeError: Cannot read property 'kickable' of undefined

javascript - 如何在 Jasmine 测试中为 [object NodeList] 编写测试用例?

javascript - jQuery中,如何在指定元素后加载ajax内容

c# - 是否有必要在 C# 中显式删除事件处理程序

php - 领域驱动设计 - 聚合 - EventPublisher with Doctrine