[英]How to search inside an element by coordinates in javascript and HTML
Lets say that I have an element that is a div. 可以说我有一个div元素。 It is 500x500 pixels.
它是500x500像素。 Inside of it are many boxes that have absolute positioning to the larger div.
它的内部有许多盒子,它们对较大的div具有绝对的定位。 If I want to use document.elementFromPoint(), should I be getting the offset of the main div and then adding px values to search in the box.
如果我想使用document.elementFromPoint(),我应该获取主div的偏移量,然后在框内添加px值进行搜索。 Or should I be doing something like mainDiv.elementFromPoint().
还是我应该像mainDiv.elementFromPoint()这样做。
The main div has relative positioning and the other divs have absolute positioning. 主div具有相对定位,其他div具有绝对定位。
I have been unable to look for elements within the box using elementFromPoint, is there something that I am not understanding about the way that positioning works? 我无法使用elementFromPoint在框中查找元素,关于定位的工作方式我是否不了解?
Access and test this pen 访问并测试这支笔
This will make you understand the thing that document.elementFromPoint(); 这将使您了解document.elementFromPoint();的含义。 only works with document.
仅适用于文档。
JS JS
function changeColor(newColor) {
elem = document.elementFromPoint(250, 150);
elem.style.backgroundColor = newColor;
}
changeColor('#dd4d39');
HTML HTML
<div class="main">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
CSS CSS
.main {
width: 500px;
height: 500px;
margin: 50px;
background: #eee;
display: inline-block;
position: relative
}
.main div {
width: 98px;
height: 98px;
margin: 1px;
background: #ddd;
display: inline-block;
position: absolute
}
.main div:nth-child(2) {
top: 0;
left: 100px;
}
.main div:nth-child(3) {
top: 100px;
left: 0;
}
.main div:nth-child(4) {
top: 0;
left: 200px;
}
.main div:nth-child(5) {
top: 200px;
left: 0;
}
.main div:nth-child(6) {
top: 0;
left: 300px;
}
.main div:nth-child(7) {
top: 300px;
left: 0;
}
Reference document.elementFromPoint(); 参考document.elementFromPoint();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.