我想做什么
我想获取特定元素 .main
的高度中心并获取那里的 DOM 元素。
我尝试了什么
我想我可以用 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);
但无论哪种情况,检索到的 DOM 元素都不是预期的那样。
显然 elementFromPoint()
似乎获取基于 viewport 的 DOM 元素。
我想使用 caretPositionFromPoint()
,但只有少量浏览器支持,这是不可能的。
问。有没有更好的方法来获取 particular 元素中的 DOM 元素?
最佳答案
您正在获取高度和宽度中心,但没有为文档的左侧和顶部添加主偏移量
我通过将您的演示调整为以下内容找到了 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
关于javascript - 如何获取特定元素中的 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663541/