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

标签 javascript html ecmascript-6

我想做什么

like this

我想获取特定元素 .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

DEMO

关于javascript - 如何获取特定元素中的 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663541/

相关文章:

javascript - 如何清除在组件生命周期中创建的 setTimeout?

javascript - JavaScript 中的奇怪语法

javascript - 如何使用jquery计算高度

jquery - CSS3 push move div 相对于其他div 移动

php - 注销时重定向并显示 "You have successfully logged out!"

Javascript Promise、then 和 catch 方法的返回 Promise

自动完成/自动填充的 Javascript 代码会减慢调查速度

javascript - dojo 1.4 阻止是/否对话框替换 window.confirm

Javascript 原型(prototype)继承 : problem when parent and child receive same object as argument?

javascript - ES6 : How to use await with callbacks