javascript 在 iPad 上处理 mouseenter 和 mouseleave

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15600511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:21:37  来源:igfitidea点击:

Dealing with mouseenter and mouseleave on the iPad

javascriptjqueryhtml

提问by Mark

I have a typical looking drop down menu that is hidden by default but by the following jQuery magic

我有一个典型的下拉菜单,默认情况下隐藏,但通过以下 jQuery 魔法

<ul class="navNew">
    <li  class="test">
        <a href="#">OPTION</a>
        <ul>
            <li>Suboption -- Hidden</li>
        </ul>
    </li>
</ul>

$(".navNew li").unbind('mouseenter mouseleave').bind('mouseenter mouseleave', function() {
    $(this).toggleClass('hover');                                  
});

So with a mouseenter and a mouseleave, the class "hover" is added to the menu to make it visible or toggle it off to make it invisible again.

因此,使用 mouseenter 和 mouseleave 类,将“悬停”类添加到菜单中以使其可见或将其关闭以使其再次不可见。

This all works like a charm, problem is on the iPad. A single click will act as a mouseenter, but clicking the button again does not act as a mouseleave, and so the menu never closes again. Can this code be modified so that a click will open and close this menu as well?

这一切都像魅力一样,问题出在 iPad 上。单击一次将充当鼠标输入,但再次单击按钮不会充当鼠标离开,因此菜单永远不会再次关闭。可以修改此代码以便单击也可以打开和关闭此菜单吗?

I've created a jsFiddle to explain what my menu is doing: http://jsfiddle.net/qgrt5/

我创建了一个 jsFiddle 来解释我的菜单在做什么:http: //jsfiddle.net/qgrt5/

采纳答案by What have you tried

Working example: http://jsfiddle.net/qgrt5/

工作示例:http: //jsfiddle.net/qgrt5/

Edit: The below code will now check if the user is coming from an iPad, and if they are, it will use the clickfunction instead of the mouseenter

编辑:下面的代码现在将检查用户是否来自 iPad,如果是,它将使用该click功能而不是mouseenter

var isiPad = navigator.userAgent.match(/iPad/i) != null;

if (isiPad) {
    $(".navNew li").unbind('mouseenter mouseleave').bind('mouseenter mouseleave', function() {
        $(this).toggleClass('hover');                                       
    });
}
else {
  $(".navNew li").unbind('mouseenter mouseleave').bind('mouseenter mouseleave', function() {
        $(this).toggleClass('hover');                                       
   });
}