如何在调整窗口大小时重置事件

时间:2019-07-09 07:28:24

标签: javascript jquery

我正在构建响应式菜单。当我在1100px以下时,我想显示菜单按钮,而在上面我显示普通的水平菜单。我首先检查$(window).width(),如果宽度小于1100px,则会触发一些事件,如果不是,则会触发另一个事件。

“我的菜单”按钮(适用于1100像素以下)具有点击事件。当我第一次使用大于1100px(例如1300px)的窗口,然后为移动设备调整大小时,此click事件不起作用。

仅当我重新加载页面时,它才起作用。

$(document).ready(function() {
  if($(window).width() < 1100) {
    $('.menu-button').click(function(e) {
      $('#menu-body').slideToggle();  
      $(this).parent().siblings().children().children().removeClass('active');
    });

    $('.menu-top').click(function(e) {
      $(this).parent().siblings().children().removeClass('active');
      $(this).siblings().addClass('active');
    });

  } else {
    $('.menu-top').mouseover(function(e) {
      $(this).parent().parent().children().children().removeClass('active');
      $(this).siblings().addClass('active');
      $(this).parent().addClass('active-top');
    });

    $('.menu-point').mouseleave(function(e) {
      $(this).removeClass('active-top');
      $(this).children().removeClass('active');
    });
  }
});

1 个答案:

答案 0 :(得分:0)

问题在于,仅在文档加载完成($(document).ready)时才设置单击/鼠标事件侦听器。 在页面加载完成后和刷新后调用。

每当窗口大小从任一方向通过断点时,您都​​需要再次调用此代码。

jQuery on window resize

就您而言,

function foobar() {
    if($(window).width() < 1100) {
        $('.menu-button').click(function(e) {
            $('#menu-body').slideToggle();  
            $(this).parent().siblings().children().children().removeClass('active');
        });

        $('.menu-top').click(function(e) {
            $(this).parent().siblings().children().removeClass('active');
            $(this).siblings().addClass('active');
        });
    } else {
        $('.menu-top').mouseover(function(e) {
            $(this).parent().parent().children().children().removeClass('active');
            $(this).siblings().addClass('active');
            $(this).parent().addClass('active-top');
        });

        $('.menu-point').mouseleave(function(e) {
            $(this).removeClass('active-top');
            $(this).children().removeClass('active');
        });
    }
}
$(document).ready(foobar);
$(window).on('resize', foobar);