JQuery .on(“click”) triggers “mouseover” on touch device

只愿长相守 提交于 2019-12-23 17:41:32

问题


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

Code:

$(".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!");
}

Problem:

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!

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?

My JQuery version is 2.2.4.


回答1:


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.
}

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.



来源:https://stackoverflow.com/questions/37403733/jquery-onclick-triggers-mouseover-on-touch-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!