【发布时间】:2020-11-13 07:32:01
【问题描述】:
我正在制作游戏,我使用的是 div 而不是 canvas.rect,我希望一个 div 始终位于另一个 div 内。我在编写一个看起来像这样的测试脚本时遇到了这个问题。
var mousex, mousey;
function mousepos(e){
mousex = e.clientX;
mousey = e.clientY;
document.getElementById("xy").innerText = mousex + " , " + mousey;
}
function testdiv(){
document.getElementById("testdiv").style.left = mousex;
document.getElementById("testdiv").style.top = mousey;
setTimeout(testdiv, 30);
}
#city{
border: 1px dotted white;
background-color: lightgreen;
height: 500;
width: 500;
resize: both;
overflow: hidden;
max-height: 500px;
max-width: 500px;
min-height: 100px;
min-width: 100px;
}
#xy{
color: white;
}
#testdiv{
background-color: white;
position: absolute;
width: 100px;
height: 100px;
}
#body{
background-color: black;
}
<body id="body" onload="testdiv()">
<center>
<div id="city" onmousemove="mousepos(event);">
<div id="testdiv"></div>
</div>
<p id="xy"></p>
</center>
</body>
当您的鼠标位于绿色的大 div 上时,代码会检测您的鼠标 X 和鼠标 Y,然后它将白色 div 的左角放在鼠标 X 和鼠标 Y 上。我的问题是当我的鼠标拖动白色 div 时向下或向右,我可以将它拖离绿色 div。
有什么办法可以解决这个问题吗?
【问题讨论】:
-
您可以在父元素上调用 Element.getBoundingClientRect() 并检查 mousex/mousey 是否大于 left/top 而小于 width/height
-
我不推荐使用递归。为了获得高性能,请使用循环。
标签: javascript html dom-events mouseover