如何检测堆叠元素的点击?

时间:2019-06-05 12:51:39

标签: javascript

我创建了一个包含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>

2 个答案:

答案 0 :(得分:1)

您可以听文档的click事件并检查鼠标位置是否在每个div的getBoundingClientRect

https://developer.mozilla.org/es/docs/Web/API/Element/getBoundingClientRect

要获取点击位置,请执行event.clientX.clientY

https://developer.mozilla.org/es/docs/Web/API/MouseEvent

答案 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>