简体   繁体   English

根据情况阻止jQuery脚本运行

[英]Prevent jQuery script from running depending on condition

I have this script which should allow slideUp/slideDown for nested ul (dropdown menu) when window is larger than 800px and disable slideUp/slideDown functionality if window's width is less than 800px and simply show all nav content as an unordered list. 我有这个脚本,当窗口大于800px时,应允许slide up / slideDown用于嵌套ul(下拉菜单);如果窗口的宽度小于800px,则应禁用slideUp / slideDown功能,并简单地将所有导航内容显示为无序列表。

Everything works as expected on 'load' event. 一切都在“加载”事件中按预期进行。

Unfortunately I can't get slideUp/slideDown animations to stop from being executed on 'resize' event after window has been resized under 800px. 不幸的是,在将窗口调整为小于800px的大小后,我无法使slideUp / slideDown动画停止在“ resize”事件上执行。

Is there a solution to this? 有针对这个的解决方法吗? Thanks 谢谢

$(window).on('load resize', function(event){
      var win = $(this); //this = window
      if (win.width() >= 800) {

        $( "nav" ).addClass( "wide-nav" );

        $('nav.wide-nav li').hover(
          function () {
            $('ul', this).stop().slideDown(200);
          },
          function () {
            $('ul', this).stop().slideUp(200);
          }
        );
    } else  { 
        $( "nav" ).removeClass( "wide-nav" );
    }
});

When the window with is bigger or equals to 800, you are binding the hover event, but when is less than 800, you are not unbinding, so try to unbind the event when you get the resize event: 当具有的窗口大于或等于800时,您将绑定hover事件,但是当小于800时,您将不取消绑定,因此请在获得resize事件时尝试取消绑定该事件:

$(window).on('load resize', function(event){
      var win = $(this); //this = window
      if (win.width() >= 800) {

        $( "nav" ).addClass( "wide-nav" );

        $('nav.wide-nav li').hover(
          function () {
            $('ul', this).stop().slideDown(200);
          },
          function () {
            $('ul', this).stop().slideUp(200);
          }
        );
    } else  { 
        $( "nav" ).removeClass( "wide-nav" );
        $('nav.wide-nav li').off('hover')
    }
});

Try using jQuery's .off() function. 尝试使用jQuery的.off()函数。 In my simple example, it removes resize event handler from window element once window width gets less than 400 pixels. 在我的简单示例中,一旦窗口宽度小于400像素,它将从window元素中删除resize事件处理程序。

EDIT: open snippet in the full page to be able to resize it. 编辑:在整页中打开代码段即可调整大小。

 function resizeEventHandler(event) { console.log("Resized"); var win = $(this); console.log(win.width()); if (win.width() < 400) { win.off("resize", "", resizeEventHandler); } } $(window).on('load resize', resizeEventHandler); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 

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

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