2016-09-19 58 views
0

我正在研究JavaScript学习项目(没有jQuery),我需要测试鼠标的水平位置是否与变量的值相同。如何测试水平鼠标位置是否等于一个变量在Javascript中

我有一个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 

    } 

我测试过它,它似乎没有工作,但有数字显示在控制台上了没有错误。

我感谢您的帮助。

+0

它有位置:绝对? –

+0

@StepanYakovenko跟随鼠标的div是绝对的,其他div是相对的 – thinoquinn

+0

这样的东西? * onmousemove = function(e){console.log(“mouse location:”,e.clientX,e.clientY); (e.clientX> 20 && e.clientX <400)console.log(“You got me:”,e.clientX,e.clientY); } } * – blackpen

回答

0

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>

+0

是的,我忘了报价。只是一个错字。这与我正在寻找的东西非常接近。我可以使用它。 :) 谢谢! – thinoquinn

+0

我把语句改成了'if(x> = otherVar && x <= otherVar + 100)'这样div就会变成绿色,只要它在蓝色之下,但是如果它在另一边 – thinoquinn

相关问题