Jquery mousemove() gets activated without a mouse

2019-04-11 04:24发布

I am trying to do a google.com like fade in (Cept i want to fade out text)

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
  $(document).ready(function() {
    $("html").mousemove(function () {
      $("p").fadeOut("slow");
    });
  });
</script>

With that code, my fade out gets automatically activated although I have not moved the mouse. Happens in all browsers. Any tips?

3条回答
forever°为你锁心
2楼-- · 2019-04-11 04:56

It seems that if the page loads and the mouse is present on the page once the page has loaded it will fire an event. Try hiding your mouse from the page by leaving it over the address bar or somewhere over the menu at the top of your browser, refresh the page with F5 and notice that the event is not fired. Similarly, try refreshing with F5 and immediately right click on the page. Keep your mouse over the page but make sure that the context menu is still open. Once the page has loaded, without moving your mouse at all, hit the Escape key on your keyboard so the mouse will exit the context menu and return to the page. The mouse has not moved but has been detected on the page and the event is triggered.

Tested in Chrome 5 on Windows 7. Too lazy to try another browser but I assume it's the same thing.

查看更多
劳资没心,怎么记你
3楼-- · 2019-04-11 05:06

Since the event fires once initially and mousemove fires every time you move it a pixel, you could just ignore the very first (possibly automatic, depending on browser) mousemove event to get the effect you want, like this:

$(function() {
  var moveCount = 0;
  $("html").mousemove(function () {
    if(moveCount++ === 0) return; //first run?
    $("p").fadeOut("slow");
    $(this).unbind('mousemove'); //unbind this, no need to stick around
  });
});​

You can try a demo here, all we're doing is ignoring the very first firing of the mousemove event, after that we do the fade and unbind this handler so that it doesn't run for future mousemove firings, just cleaning up.

查看更多
Lonely孤独者°
4楼-- · 2019-04-11 05:07

Are you sure there is not 'micro movements'? Sometimes an optical mouse can causes movements to register just with dust or dirt.

查看更多
登录 后发表回答