在 mouseleave 或 touchend 上切换 class

Toggle class on mouseleave or touchend

我正在尝试让 jQuery 下拉菜单在移动设备和桌面设备(触摸和非触摸设备)上都可用。

一切都按预期工作,但我无法让 'selected' class 切换 on/off。另外,如果您有任何提高性能的建议,请告诉我。

$(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

感谢您的帮助。

$(函数(){

$('li.dropdown > a').on('click',函数(事件){

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