简体   繁体   English

jQuery切换无法调整大小

[英]jQuery toggle not working on resize

When I resize the window, the toggle part is not working, I had to refresh the page again(keeping the window in the resized state) and it works fine. 当我调整窗口大小时,切换部分不起作用,我不得不再次刷新页面(将窗口保持在调整大小状态),并且工作正常。

bodyClass() part is working fine, just not the menu() part. bodyClass()部分可以正常工作,而菜单()部分则不能。

Please help :) 请帮忙 :)

    jQuery(document).ready(function() {

    function menu(){

        var memberAreaWidth = jQuery(window).width();
        if( memberAreaWidth <= 900 ){

            jQuery('.memebers-menu').css('display', 'none');
            jQuery('.memebers-header-logo span').click(function(){

                jQuery('.memebers-menu').toggle();

            });         
        }


    }

    function bodyClass(){           

        var memberAreaWidth = jQuery(window).width();
        if( memberAreaWidth > 900 ){
            jQuery('body').addClass('fullwidth');
        }else{
            jQuery('body').removeClass('fullwidth');
        }

    }

    jQuery(window).on("load resize",function(){

        menu();
        bodyClass();

    });

});

Move the click event delegation so it only happens once. 移动单击事件委托,使其仅发生一次。 The rest of the code looks fine. 其余代码看起来不错。

var smallWidth = false;

jQuery('.memebers-header-logo span').click(function(){
    if (smallWidth){
        jQuery('.memebers-menu').toggle();
    }
});  

function menu(){

    var memberAreaWidth = jQuery(window).width();
    if( memberAreaWidth <= 900 ){

        jQuery('.memebers-menu').css('display', 'none');
        smallWidth = true;
    } else {
        smallWidth = false;
    }


}

Simplify your code a bit, put the event handlers outside the functions so they do not re-bind each time the function is called (which would end up with multiple event handlers firing); 稍微简化代码,将事件处理程序放置在函数之外,以免每次调用函数时它们都不会重新绑定(最终会触发多个事件处理程序); pass a parameter so you only have to calculate it once. 传递参数,因此您只需计算一次。

jQuery(document).ready(function() {
  jQuery('.memebers-header-logo span').on('click', function() {
    jQuery('.memebers-menu').toggle();
  });
  jQuery(window).on("load resize", function() {
    var memberAreaWidth = jQuery(window).width();
    menu(memberAreaWidth);
    bodyClass(memberAreaWidth);
  });

  function menu(memberAreaWidth) {
    if (memberAreaWidth <= 900) {
      jQuery('.memebers-menu').hide();
    }
  }

  function bodyClass(memberAreaWidth) {
    if (memberAreaWidth > 900) {
      jQuery('body').addClass('fullwidth');
    } else {
      jQuery('body').removeClass('fullwidth');
    }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM