【问题标题】:Toggle class on mouseleave or touchend在 mouseleave 或 touchend 上切换类
【发布时间】:2017-11-11 04:20:56
【问题描述】:

我正在尝试让 jQuery 下拉菜单同时在移动设备和桌面设备(触摸和非触摸设备)上工作。

一切都按预期工作,但我无法让“选定”类打开/关闭。另外,如果您对提高性能有任何建议,请告诉我。

$(function(){

  $('li.nav__main__item--has-children > a').on('click',function(event){

    event.preventDefault();

    $(this).toggleClass('selected');

    $(this).parent().find('ul').first().toggle(300);

    $(this).parent().siblings().find('ul').hide(200);

    //Hide menu when clicked outside
    $(this).parent().find('ul').on('mouseleave touchend',(function(){ 
      var thisUI = $(this);

      $('html').click(function(){
        thisUI.hide();
        $('html').unbind('click');
      });
    }));

  });
});

这是带有完整示例的 Codepen:https://codepen.io/friendlywp/pen/WXpXWv

感谢您的帮助。

【问题讨论】:

    标签: jquery mobile touch


    【解决方案1】:

    $(函数(){

    $('li.dropdown > a').on('click',function(event){

    event.preventDefault();
    $(this).toggleClass('selected');
    $(this).parent().find('ul').first().toggle(300);
    
    $(this).parent().siblings().find('ul').hide(200);
    
    //Hide menu when clicked outside
    $(this).parent().find('ul').parent().mouseleave(function(){ 
      var thisUI = $(this);
      $('html').click(function(){
        thisUI.children(".dropdown-menu").hide();
    thisUI.children("a").removeClass('selected');
    
        $('html').unbind('click');
      });
    });
    

    });

    });

    https://codepen.io/piscu/pen/EbWQda

    【讨论】:

    • unbind 已弃用,应使用 off
    • 感谢@user8909141,但该示例不起作用...... .selector 类没有被删除。它的行为似乎和我原来的一模一样...?
    • @Michelle 你能再看看吗
    猜你喜欢
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多