控制状态

时间:2015-12-08 01:33:32

标签: javascript onmouseover onmousemove

getMouseXY = function(e) {
  tempX = e.pageX
  tempY = e.pageY 

  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  

  document.getElementById("circle1").style.top = (tempY - 25) + "px";
  document.getElementById("circle1").style.left = (tempX - 25) + "px";
  return true
}

document.onmousemove = getMouseXY;

trackCircle = function() {
  document.getElementById("circle1").style.top = "10px";
  document.getElementById("circle1").style.left = "10px";
}

document.getElementById("circle1").addEventListener("click", trackCircle);
<div id="circle1" style="width:50px;height:50px;background-color:orange;border-radius:50px;position:absolute;"></div>

这个想法是圆圈跟踪你的鼠标,直到你点击,然后它回到它的休息点。问题是,当我再次移动鼠标时,它会撤消静止位置,然后返回跟踪文档.onmousemove计划是在重新悬停“circle1”之后才恢复跟踪,一旦休息,...然后继续跟踪document.onmousemove

我知道我可以调用类似这样的东西而不是document.onmousemove:

document.getElementById("circle1").addEventListener('mousemove', getMouseXY);

但是“鼠标是否悬停在这个特定的元素上?”事件是不精确的,当你快速移动鼠标时,你最终会丢失很多跟踪。

似乎我需要构建某种状态机,其中包括trackingON或trackingOFF。通过单击圆圈触发trackingOFF并通过悬停圆圈触发trackON(但实际跟踪使用document.onmousemove

1 个答案:

答案 0 :(得分:0)

你需要一个标志来指定&#34;我点击了,停止跟踪我的鼠标&#34;当你点击并检查说&#34时设置;我已将鼠标移到圆圈上,继续跟踪我&#34;

这是更新的小提琴:http://jsfiddle.net/ub9v9p0j/8/

和实际代码:

var stopTracking = false;

getMouseXY = function(e) {
  tempX = e.pageX
  tempY = e.pageY 
  var circle = document.querySelector('#circle1');
  var r = circle.offsetWidth / 2;

  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  

  if (stopTracking) {
    if (Math.pow(tempX - circle.offsetLeft - r, 2) + Math.pow(tempY - circle.offsetTop - r, 2) < r * r) {
      stopTracking = false;
    } else {
        return;
    }
  }
  document.getElementById("circle1").style.top = (tempY - 25) + "px";
  document.getElementById("circle1").style.left = (tempX - 25) + "px";
  return true
}

document.onmousemove = getMouseXY;

trackCircle = function() {
  document.getElementById("circle1").style.top = "10px";
  document.getElementById("circle1").style.left = "10px";
  stopTracking = true;
}

document.getElementById("circle1").addEventListener("click", trackCircle);