我正在做一个游戏,并且我使用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。
有办法解决这个问题吗?
最佳答案
由于当前JS中没有受支持的父选择器。
您可以使用Jquery或CSS,我同时列出了Javascript选项和CSS选项
选项1:$("a.active").parents('li').css("property", "value");
选项2:Sibling Combination以匹配任何ParentElement
元素之前是ChildElement
元素。// Just change the parent and child elemets belowParentElement ~ ChildElement { property: value;}
关于javascript - 如何检测一个Div是否在另一个Div之外?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47335670/