.mousemove more effective
In a web page, I want to show some menu whenever 开发者_如何转开发the pointer is near the edge of the <div>
. I can do it with .mousemove
, check position and show / hide menu when the pointer is in a specified distance.
As jQuery manual says:
Keep in mind that the mousemove event is triggered whenever the mouse pointer moves, even for a pixel. This means that hundreds of events can be generated over a very small amount of time.
Is there some neat way to detect if a cursor is in a specified distance from the edge, not involving resource consuming .mousemove
? I thought about some invisible <div>
and catching .mouseenter()
there, but such a div would overlap with other elements and would block other events from those elements.
see the code below which can be used to calculate the distance between a div and mouse pointer
(function() {
var mX, mY, distance,
$distance = $('#distance span'),
$element = $('#element');
function calculateDistance(elem, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
}
$(document).mousemove(function(e) {
mX = e.pageX;
mY = e.pageY;
distance = calculateDistance($element, mX, mY);
$distance.text(distance);
});
})();
click here for more info
Take a look at mouseenter
and mouseleave
events they are better than mousemove
and mouseenter
combinations.
One of the ways i solved this problem is as follows, i basically coded up a producer/consumer solution, where the mousemove event is the producer and a timer is the consumer. Some untested code is below for illustration:
var pos = []
var old_pos = []
$(document).mousemove(function(e) {
pos = [e.pageX, e.pageY]
// do something else here?
});
setInterval(function(){
// do something with the fact that mouse has moved from old_pos to pos;
old_pos = [pos[0], pos[1]];
}, 100);
Personally, i've found that even if i set the interval time to 10 milliseconds, mousemove will still fire 3 times for everytime setInterval fires, so it is saving significant computation, and 10ms is plenty short for fast paced action (1000ms = 1sec, so 10ms = 100 frames per second).
精彩评论