你的位置:首页 > Java教程

[Java教程]js判断鼠标是否停止移动


本程序实现当鼠标在一个特定的div内悬停n秒时,判断出已经停止移动。

思路:

1.定义全局变量鼠标移动状态imouse,定时器timer。当鼠标在div内移动时,imouse值为1,相反静止时值为0;timer可以实现每过n秒就判断鼠标状态,然后把imouse重置为0;

2.div监听onmouseover。当鼠标进入区域时,就设置定时器;

3.div监听onmousemove。当鼠标移动时,设置imouse值为1;

4.div监听onmouseout。当鼠标离开时,清除定时器timer

<html>  <head>    <meta http-equiv="charset" content="utf-8" />    <script type="text/javascript">      var tip;      var imouse = 0;      var timer;      function startup() {        tip = document.getElementById("tip");      }      function mouseIn() {        timer = window.setInterval(foo, 1000);      }      function mouseOut() {        window.clearInterval(timer);      }      function mouseMove() {        imouse = 1;        tip.innerHTML = "move";      }      var foo = function() {        if (imouse == 0) {          tip.innerHTML = "still";        }        imouse = 0;      }    </script>  </head>  <body onload="startup()">    <div id="imgArea" onmousemove="mouseMove()" onmouseover="mouseIn()" onmouseout="mouseOut()">      <!-- 这里随便放一些东西 -->    </div>    <div id="tip"></div>  </body></html>