MouseMove event repeating every second

后端 未结 3 1104
不思量自难忘°
不思量自难忘° 2020-12-30 08:55

http://jsfiddle.net/MrkY9/

My computer (and so far, no other computer among my coworkers) is exhibiting an issue in Chrome, IE, and Safari (but not in Firefox). Sim

3条回答
  •  [愿得一人]
    2020-12-30 09:41

    For me the issue happens sometimes when iTunes is playing. I know iTunes (for Windows) has had a focus issue for ages - it tends to steal focus from its own popup windows.

    You pointed out the problem in your (accepted) answer: other applications can steal the browser's focus, firing the mousemove event at will. However for a live website we cannot assume a user is not running certain programs like Task Manager or iTunes.

    As suggested in the question's comment section, please save the mouse position and keep checking if it changed.

    Example code using jQuery:

    var old_pos = [0, 0];
    $(el).on("mousemove", function(e) {
        var new_pos = [e.clientX, e.clientY];
    
        // Quit if the mouse position did not change.
        if(old_pos[0] == new_pos[0] && old_pos[1] == new_pos[1])
            return;
    
        // Your code.
    });
    

    (Note: you're better off using the touchmove event with the touches and changedTouches arrays for touch gestures.)

    Hope this helps anyone bumping into similar problems.

    Edit: additional functionality to separate mouse events from touch events based on Scott's comment below:

    var old_pos = [0, 0];
    $(el).on("mousemove touchmove", function(e) {
        var new_pos = [e.clientX, e.clientY];
    
        // Quit if the mouse position did not change.
        if(e.type == "mousemove" && old_pos[0] == new_pos[0] && old_pos[1] == new_pos[1])
            return;
    
        // Your code.
    });
    

提交回复
热议问题