简体   繁体   中英

The mouse position when firing mouseleave() event in Firefox

I was trying to detect where did the mouse go after the mouseleave() event has been fired.

$( "#menu li" )
.mouseleave(function(e) {       
    if($('#menu li:hover').length==0){
          //the mouse left menu         
    }else{

          //the mouse is pointing to another li
    }       
});

on Opera, Chrome, and IE, this works fine. But on Firefox, it seemed that the mouseleave event fires when the mouse is still inside the element. So the $('#menu li:hover').length will always have value of 1.

I came up with an ugly workaround: wrap the if statement with a setTimeout function and given the interval 1ms. Surely that won't always fix the problem.

Is there any way to work around this elegantly?

"I was trying to detect where did the mouse go after the mouseleave() event has been fired."

I'm just going to focus on this part of the question, because your solution to that problem isn't great. Instead you should just use the e.relatedTarget property. That'll give you the node that the pointer entered upon leaving the li .

 $( "#menu li" ).mouseleave(function(e) { document.querySelector("pre").textContent += ("\\nLeave LI, Enter " + e.relatedTarget.nodeName); }); 
 ul { padding: 30px; background: orange } li { padding: 10px; background: yellow } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <ul id="menu"> <li>first <li>second <li>third </ul> <pre></pre> 

The docs even give an example similar to yours:

http://api.jquery.com/event.relatedTarget/

 $( "a" ).mouseout(function( event ) { alert( event.relatedTarget.nodeName ); // "DIV" }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM