如何测试水平鼠标位置是否等于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>

最新更新