JQuery .on(“click”)触发“鼠标悬停”。在触摸设备上 [英] JQuery .on("click") triggers "mouseover" on touch device

查看:110
本文介绍了JQuery .on(“click”)触发“鼠标悬停”。在触摸设备上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在触控设备上使用JQuery的 $。on(click,function(){}); 时,我遇到了不必要的行为。这是我的代码:

I'm encountering unwanted behavior when using JQuery's $.on("click", function(){}); on touch devices. This is my code below:

代码:

$(".team").on("mouseover", teamMouseOver);
$(".team").on("mouseout", teamMouseOut);
$(".team").on("click", teamThumbClicked);

function teamMouseOver(event){
    console.log(event.type);
}

function teamMouseOut(event){
    // Do something
}

function teamThumbClicked(event){
    console.log("Clicked!");
}

问题:

使用上面的代码,点击触摸设备上的 .team 元素同时触发两个侦听器,给我以下控制台日志:

With the code above, tapping on a .team element on a touch device simultaneously triggers both listeners, giving me the following console log:

mouseover
Clicked!

问题
为什么鼠标悬停在触控设备上触发?这不是我期望从没有鼠标的设备的行为。这是一个错误吗?我应该使用什么事件,因此当鼠标指针正在进入时,mouseover才被触发?

Question Why is mouseover being triggered on a touch device? This is not the behavior that I would expect from a device that doesn't have a mouse. Is this a bug? What event should I be using so "mouseover" only gets fired when it's an actual mouse pointer that's entering?

我的JQuery版本是2.2.4。

My JQuery version is 2.2.4.

推荐答案

我刚遇到同样的问题,这就是我为解决问题所做的工作。

I just ran into the same issue and this is what I did to solve the problem.

$('#myEl').on('click', myElClickEvent);

$('#myEl').on('mouseenter', myElMouseEnterEvent);

function myElClickEvent (event) {
   $(this).addClass('Clicked');
}

function myElMouseEnterEvent() {
    // Turn off events
    $('#myEl').off();

    // After 100 milliseconds cut on events, notice click event won't trigger
    setTimeout(function() {
       // .off() is used to prevent from adding multiple click events if the user hovers multiple elements too quickly.
       $('#myEl').off().on('click', myElClickEvent);             
       $('#myEl').off().on('mouseenter', myElMouseEnterEvent);
    }, 100);


   // Do some mouseenter stuff, whatever the reqs. are.
}

这就是我所做的,它在我的用例中运行良好。希望这可以帮助将来的某个人。我们的想法是关闭鼠标输入事件中的单击事件,然后在100毫秒后重新打开鼠标单击事件。这样可以防止两个事件在触​​摸时触发。

This is what I did and it worked fine for my use case. Hopefully this helps someone in the future. The idea is to turn off the click event within the mouse enter event and then after 100 milliseconds cut the mouse click event back on. This will prevent both events from triggering on touch.

这篇关于JQuery .on(“click”)触发“鼠标悬停”。在触摸设备上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆