JavaScript in Chrome
I have a div which onmouseover
, displays a panel and onmouseout
makes it disappear. JavaScript code is as 开发者_StackOverflowfollows:
function ShowPanel() {
document.getElementById("thePanel").style.display = "inline";
}
function HidePanel() {
document.getElementById("thePanel").style.display = "none";
}
The code works in Firefox and IE perfectly. The problem is Chrome. It works until the mouse is on the textbox in the panel. When the mouse goes on the textbox the onmouseout
event is called even though the textbox is part of the panel and should remain open.
What you need is the behavior of the onmouseenter event instead of onmouseover and onmouseleave instead of onmouseout. The problem is that those events work only in IE (they actually got those ones right). You either need to simulate that behavior taking into account all of the differences in the event handling in different browsers, or just use a good JavaScript library that would take care of that for you. For example jQuery has .mouseenter() and .mouseleave() that are simulated on browser that don't support those events natively, and even a nice shortcut .hover() to set both at the same time.
I wouldn't recommend doing it manually unless you really know all of the quirks and inconsistencies of event models in different browsers (and you don't since you asked this question) but if you want to see how jQuery is doing it then see events.js and search for mouseenter
and mouseleave
.
In Chrome as you've found the mouseout
event is fired whenever you move from the parent element (on which the handler is registered) and child elements contained within it.
The simple fix is to use jQuery, which will simulate mouseleave
events (which don't suffer that problem) on browsers that don't support it.
Alternatively, in your mouseout
handler, look at the toElement
property of the event, and traverse its parent list and see if your original parent is in that list. Only process your action if it was not in the list.
document.getElementById('outer').addEventListener('mouseout', function(ev) {
var el = ev.toElement;
while (el && el !== document.body) {
if (el === this) {
console.log('mouseout ignored');
return; // enclosed - don't do anything
}
el = el.parentNode;
}
console.log('mouseout');
}, false);
demo at http://jsfiddle.net/raybellis/s4EQT/
精彩评论