我创建了一个包含3个DIV的演示,这些DIV有点堆叠/重叠。如果单击的点超过一个div,则仅弹出“最高” DIV的警报。如何检测该点所有DIV的点击?
document.getElementsByClassName("testBox")[0].onclick = () => {
alert("test 1");
}
document.getElementsByClassName("testBox")[1].onclick = () => {
alert("test 2");
}
document.getElementsByClassName("testBox")[2].onclick = () => {
alert("test 3");
}
.testBox {
width: 400px;
height: 200px;
background: lightblue;
margin: 30px;
border: 2px solid black;
opacity: 0.7;
}
.testBox:nth-child(2) {
position: relative;
top: -100px;
left: 30px;
}
.testBox:nth-child(3) {
position: absolute;
top: 50px;
left: 300px;
}
<div class="testBox"></div>
<div class="testBox"></div>
<div class="testBox"></div>
答案 0 :(得分:1)
您可以听文档的click事件并检查鼠标位置是否在每个div的getBoundingClientRect
内
https://developer.mozilla.org/es/docs/Web/API/Element/getBoundingClientRect
要获取点击位置,请执行event.clientX
或.clientY
答案 1 :(得分:-1)
创建一个包含所有div
的父项div
。
document.getElementsByClassName("testBox")[0].onclick = () => {
alert("test 1");
}
document.getElementsByClassName("testBox")[1].onclick = () => {
alert("test 2");
}
document.getElementsByClassName("testBox")[2].onclick = () => {
alert("test 3");
}
document.getElementsByClassName("par")[0].onclick = () => {
alert("par");
}
.testBox {
width: 400px;
height: 200px;
background: lightblue;
margin: 30px;
border: 2px solid black;
opacity: 0.7;
}
.testBox:nth-child(2) {
position: relative;
top: -100px;
left: 30px;
}
.testBox:nth-child(3) {
position: absolute;
top: 50px;
left: 300px;
}
<div class="par">
<div class="testBox"></div>
<div class="testBox"></div>
<div class="testBox"></div>
</div>