jQuery 的 mouseleave 事件在触屏设备/平板电脑上如何实现?

13

我有一个模态框,它会在mouseenter时淡入并在mouseleave时淡出。唯一的问题是当使用触摸屏设备,如平板电脑时,我无法让模态框在显示后fadeout。是否有一种方法可以修改此代码,使用户每次触摸模态框外部时都会fadeout

$(".tiptrigger").mouseenter(function() { 

    var s_id = $(this).attr('id'); // There may be more than one per page
    $("#tiptip_holder-"+s_id).fadeIn("fast");   

}); 

$(".tiptrigger").mouseleave(function() { 

    var s_id = $(this).attr('id');
    $("#tiptip_holder-"+s_id).fadeOut("slow");

}); 
2个回答

19

您可以尝试使用触摸事件(未经测试):

$('.tiptrigger').on('mouseenter touchstart', function(){ 
    var s_id = $(this).attr('id'); // There may be more than one per page
    $("#tiptip_holder-"+s_id).fadeIn("fast"); 
});

$('.tiptrigger').on('mouseleave touchend', function(){
    var s_id = $(this).attr('id');
    $("#tiptip_holder-"+s_id).fadeOut("slow");
});

编辑

您可以尝试:

$('.tiptrigger').on('mouseenter touchstart', function(e){ 
    var s_id = $(this).attr('id'); // There may be more than one per page
    $("#tiptip_holder-"+s_id).fadeIn("fast"); 
    e.stopPropagation()
});

$('.tiptrigger').on('mouseleave', function(e){
    var s_id = $(this).attr('id');
    $("#tiptip_holder-"+s_id).fadeOut("slow");
});

$('body').on('touchstart', function(e){ 
    $("div[id^='tiptip_holder']").fadeOut("slow");        
});

谢谢,但我想要做的是,无论何时用户触摸页面,如果模态框可见,则隐藏它。 - MultiDev
你想关闭任何可以打开的tiptip holder吗? - Irvin Dominin
是的,如果任何 tiptop_holder 是可见的,当触摸到 body 时我想要隐藏所有的 tiptop_holder。我一直在尝试,但是在它隐藏一次之后,我无法让它重新出现。 - MultiDev
非常感谢!使用body的touchstart存在问题,因为.tiptrigger位于body内部,所以它现在正在尝试同时打开和关闭。有没有一种方式,而不是$('body').on('touchstart'),基本上声明如果除了.tiptrigger之外的任何东西都被触摸,则执行一些操作?这样就可以解决问题了。 - MultiDev
我需要知道它是如何工作的,它是打开一个覆盖层div吗?您能在jsfiddle上提供一个快速示例吗? - Irvin Dominin
所有的 div 都在页面上,但是被隐藏了。 - MultiDev

10
鼠标事件(mouseovermouseoutmousedownmouseupmousemove等)是特定于鼠标输入设备的。键盘具有 keydown keypress keyup 。触摸屏具有 touchstart touchmove touchend touchcancel 。iPhone / iPad等上的Webkit具有其他手势开始/移动/结束事件,这些事件是Apple特定的。

因此,您应该检查运行应用程序的设备,然后相应地处理代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接