问题描述
我要获取特定元素 .main
的高度的中心,并获取其中的DOM元素。
I want to get the center of the height of a specific element .main
and get the DOM element that is there.
我以为我可以得到一个带有 elementFromPoint()
的DOM元素。
I thought I could get a DOM element with elementFromPoint()
.
①
// 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()
似乎基于视口获得了DOM元素。
But in either case, the retrieved DOM element was not as expected.
Apparently elementFromPoint()
seems to get DOM elements based on viewport.
我想使用,但是只有少量浏览器支持,这是不可能的。
I wanted to use caretPositionFromPoint()
, but with a small amount of browser support, this is not possible.
问。有没有更好的方法来在 specific 元素中获取DOM元素?
Q. Is there any better way to get DOM elements in a particular element?
推荐答案
您将获得高度和宽度中心,但未添加main从文档左侧和顶部的偏移量
You are getting height and width centers but not adding the offsets for main from left and top of the document
通过将您的演示调整为以下内容,我发现元素 p.active
:
I found element p.active
by adjusting your demo to:
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
这篇关于如何获取特定元素中的DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!