Javascript如何测试鼠标水平位置是否等于某个变量

How to test whether horizontal mouse position is equal to a variable in Javascript

我正在做一个javascript学习项目(没有jQuery),我需要测试鼠标的水平位置是否与变量的值相同。

我有一个div跟着鼠标转,当它的水平位置与另一个div的水平位置相等时,我想做点什么。

这是我得到的:

    var x = e.clientX; 

    var otherVar = 200;

    document.getElementById('testDiv').style.left = otherVar + "px";

    if (x == otherVar) {

        //do stuff

    } else {

        //do other stuff

    }

我已经测试过了,它似乎不起作用,但是控制台上没有显示任何错误。

感谢您的帮助。

document.getElementById 需要一个字符串,您需要监听 mousemove 事件:

这应该可以帮助您指明正确的方向。祝你好运。

//define your vars:
var otherDiv = document.getElementById("otherDiv"),
    testDiv = document.getElementById("testDiv"),
    otherVar = otherDiv.offsetLeft; //otherDiv's left position in px
//add event listener:
document.addEventListener("mousemove", onmousemove);
//handle the event:
function onmousemove(e) {
  var x = e.clientX; //get the current x position
  testDiv.style.left = x + "px"; //move testDiv
  if (x >= otherVar) {
    //do stuff
    testDiv.style.backgroundColor = "green";
  } else {
    //do other stuff
    testDiv.style.backgroundColor = "red";
  }
};
body {
  margin:0;
  background: #eee;
}
#otherDiv {
  position: relative;
  margin-left: 30%;
  width: 70%;
  height: 20px;
  background-color: blue;
}
#testDiv {
  position: absolute;
  left: 0;
  top: 20px;
  width: 100px;
  height: 100px;
  background-color: red;
}
<div id="otherDiv">otherDiv</div>
<div id="testDiv">testDiv</div>