简体   繁体   English

如何获取特定元素中的 DOM 元素?

[英]How to get DOM elements in a particular element?

What I want to do我想做的事

像这样

I want to get the center of the height of a specific element .main and get the DOM element that is there.我想获取特定元素.main的高度中心并获取那里的 DOM 元素。


What I tried我试过的

I thought I could get a DOM element with elementFromPoint() .我以为我可以使用elementFromPoint()获得一个 DOM 元素。

// Get the center of the height of .main
const rect = document.getElementsByClassName("main")[0].getBoundingClientRect();
const mainHCenter = rect.height / 2;
const mainWCenter = rect.width / 2;

// Get the element at the center of the height of .main
var centerElm = document.elementFromPoint(0, mainHCenter);

// Get the center of the height of .main
const main = document.querySelector(".main");
const centerY = main.offsetHeight / 2;
const centerX = main.offsetWidth / 2;

// Get the element at the center of the height of .main
const element = document.elementFromPoint(centerX, centerY);

But in either case, the retrieved DOM element was not as expected.但在任何一种情况下,检索到的 DOM 元素都不是预期的。
Apparently elementFromPoint() seems to get DOM elements based on viewport .显然elementFromPoint()似乎基于viewport获取 DOM 元素。


I wanted to use caretPositionFromPoint() , but with a small amount of browser support, this is not possible.我想使用caretPositionFromPoint() ,但由于浏览器支持很少,这是不可能的。

Q. Is there any better way to get DOM elements in a particular element?问:有没有更好的方法来获取特定元素中的 DOM 元素?

You are getting height and width centers but not adding the offsets for main from left and top of the document您正在获得高度和宽度中心,但没有从文档的左侧和顶部添加主要的偏移量

I found element p.active by adjusting your demo to:我找到的元素p.active通过调整你的演示,以:

const rect = document.getElementsByClassName("main")[0].getBoundingClientRect();

const mainHCenter = rect.top + (rect.height / 2);
const mainWCenter = rect.left + (rect.width / 2);
                  // ^^^^^   add left and top offsets


var centerElm = document.elementFromPoint(mainWCenter, mainHCenter);
                                        // ^^^ don't use zero

console.log(centerElm);// returned p.active

DEMO演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM