Jquery mousemove() gets activated without a mouse movement

谁说胖子不能爱 提交于 2019-12-06 07:33:20

问题


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?


回答1:


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.




回答2:


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:


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



来源:https://stackoverflow.com/questions/3129148/jquery-mousemove-gets-activated-without-a-mouse-movement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!