【问题标题】:Detect element closest to window in a collection检测集合中最靠近窗口的元素
【发布时间】:2021-01-05 16:54:08
【问题描述】:

请考虑以下示例:

const somevar = document.querySelectorAll('.someclass');

结果我们得到了一个项目的集合。如何检测哪个元素最靠近该集合中的窗口?最接近的意思不是物理位置,而是 DOM 层次结构中的位置。

我需要提一下,在某些情况下,我们可以在同一个 DOM 级别获得多个元素,在这种特殊情况下,我需要 DOM 中的最高元素。

注意:请不要使用 jquery。

【问题讨论】:

  • @Justinas 不,没有解决。我编辑了我的问题,使其更具体。
  • 怎么解决不了?你如何使用它?您必须循环您的 somevar 并应用推荐的问题解决方案
  • @Justinas 我编辑了我的问题,我不需要物理位置,而是 DOM 层次结构中的位置。
  • 你能举例说明你想要什么吗?通过 DOM 层次结构 我只了解元素数组。该数组与计算机窗口没有任何关系。

标签: javascript html dom


【解决方案1】:

您可以使用parentElement 属性遍历元素的文档树直到根,以评估每个元素的深度并通过它决定最接近根的元素:

// get all matching nodes as NodeList
const resultNodes = document.querySelectorAll(".someclass")
// convert NodeList object to Array of nodes
const results = [...resultNodes.keys()].map(key => resultNodes[key]);
// Compute the depth in the DOM tree for each element
const resultsWithDepth = results.map(result => {
    return {
        element: result,
        depth: computeDOMElementDepth(result, 0)
    }
})

getElementWithLowestDepth(resultsWithDepth);

// Computes the depth of a DOM element in an end-recursive fashion
function computeDOMElementDepth (element, currentDepth) {
    if (element.parentElement === null) {
        return currentDepth;
    }

    return computeDOMElementDepth(element.parentElement, ++currentDepth);
}

// Filters out the element highest in the DOM. (First element takes precedence)
function getElementWithLowestDepth (elements) {
    return elements.reduce((element1, element2) => {
        if (element2.depth < element1.depth) {
            return element2;
        }
        return element1;
    })
}

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 2013-03-17
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2012-03-16
    • 2017-12-15
    • 1970-01-01
    相关资源
    最近更新 更多