So i have a simple setup of a #container div, that contains a #field div. I also have an invisible #hover span that follows mouse movement (centered) and gets visible while hovering over #field.
HTML:
<body>
<div id="container" >
<div id="field"></div>
</div>
<span id="mouseHover" ></span>
</body>
JS:
$("#field").on({
mousemove: function (e) {
var left = parseInt($("#container").css("left")) || 0;
var top = parseInt($("#container").css("top")) || 0;
var newX = e.pageX - left - parseInt($("#mouseHover").css("width")) / 2;
var newY = e.pageY - top - parseInt($("#mouseHover").css("height")) / 2;
$("#mouseHover").css({ left: newX, top: newY });
console.log("MMove");
},
mouseenter: function(e){
$("#mouseHover").show();
console.log("MEnter");
},
mouseleave: function(e){
$("#mouseHover").hide();;
console.log("MLeave");
}
});
When hovering over the field though, it fires countless mouseenter and mouseleave (+ intended mousemove) events as soon as i move the mouse. This seems to be the case because the #hover span is centered around the mouse and everytime i move the mouse I technically leave #field and enter #hover, and then leave #hover and enter #field again and again, resulting in the #hover to show and hide continuously.
One solution i have is to not center the #hover around the mouse, so the mouse does not touch the bounds of the span and thus doesn't leave #field. But i want it centered ^^
The other is to give the span a negative z-index, which is no real solution because the #hover disappears behind the #field as soon as it gets a bgcolor.
JSFiddle with the problem (#hover is "flashing" when centered around mouse)
What would be the correct approach here :) ?
Try giving the #mouseHover
element a pointer-events
CSS property value of 'none'. Here is an updated JSFiddle .
#mouseHover {
// ...
pointer-events: none;
}
One solution i have is to not center the #hover around the mouse, so the mouse does not touch the bounds of the span and thus doesn't leave #field.
That one you could easily achieve in modern browsers, by using pointer-events
to make it “untouchable” by the mouse cursor:
#mouseHover {
pointer-events: none;
}
https://jsfiddle.net/6rauo9ba/3/
That of course will only be a solution, if you don't need to interact with the content inside the #mouseHover
element in any way.
And you might want to check browser support, to see what older browsers you might need a fallback solution for. http://caniuse.com/#feat=pointer-events
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.