jQuery how to prevent mouseenter triggering when page loads with cursor hovering element

浪子不回头ぞ 提交于 2019-12-10 17:38:22

问题


I have an element on my page with a mouseenter event bound to it which changes the dimensions of a child image.

It works just as I want, however if you hit the page with your cursor hovering where the div will be, it triggers as soon as it loads - this is undesired, I want it to do nothing until a mouse cursor actualy enters the div rather than just being there to start with.

I've tried knocking up an example on jsfiddle but the page loads too quickly for me to get the cursor in the right place :(

One possibility is putting the bind method calls in a timeout so that it takes a second to bind the event, but the problem will still happen if the user leaves their cursor over my div.

Any ideas?

Using jQuery 1.6.2


回答1:


Hm. Its only idea.

var mouse_already_there = false;
var event_set = false;
$(document).ready(function() {
    $(item).hover(function(){
        if(!event_set) { mouse_already_there = true; }
    }, function(){
        if(!event_set) { mouse_already_there = false; }
    });
    if(mouse_already_there) {
        //do nothing
    } else {
        event_set = true;
        //set event
    }
});



回答2:


My working solution is:

    var mouseenterno = 0;

    $('.selector').on('mouseenter', function() {

       //your code here

        mouseenterno = mouseenterno + 1;

    });

    $('.selector').on('mouseleave', function() {

        if (mouseenterno >= 1){

           //your code here

        }

    });


来源:https://stackoverflow.com/questions/7553442/jquery-how-to-prevent-mouseenter-triggering-when-page-loads-with-cursor-hovering

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