gpt4 book ai didi

javascript - DOM 中元素之间的“距离”(生成深度等)

转载 作者:行者123 更新时间:2023-12-02 18:16:56 28 4
gpt4 key购买 nike

我正在寻找一个函数,它可以返回 DOM 中元素之间的“距离”(以祖先、 sibling 和后代为单位)。例如,假设我有:

<div id="div1">
<div id="div5"></div>
</div>
<div id="div2">
<div id="div6">
<div id="div9"></div>
</div>
<div id="div7"></div>
</div>
<div id="div3"></div>
<div id="div4">
<div id="div8">
<div id="div10"></div>
</div>
</div>

然后我想要一个函数来返回 #div5#div10 之间的距离,如下所示:

{
up: 1,
across: 3,
down: 2
}

由于要从 #div5#div10,您必须向上一代,转发 3 个 sibling (到 #div4)并且然后下降了2代。同样,#div9#div1 将返回:

{
up: 2,
across: -1,
down: 0
}

向上两代,然后返回一个 sibling 。

我已经有了一个可以执行此操作的函数(我将在下面将其作为答案包含在内),因此我将其包含在此处,因为 a)我认为其他人可能会发现它有用; b) 也许其他人有更好的方法。

最佳答案

好的,这就是我所拥有的。我希望在代码注释中对其进行了足够好的解释:

function DOMdistance(elem1,elem2) {

if (elem1 === elem2) {
return {
up: 0,
across: 0,
down: 0
};
}

var parents1 = [elem1],
parents2 = [elem2],
gens = 1,
sibs = 0,
sibElem;

// searches up the DOM from elem1 to the body, stopping and
// returning if it finds elem2 as a direct ancestor
while (elem1 !== document.body) {
elem1 = elem1.parentNode;
if (elem1 === elem2) {
return {
up: parents1.length,
across: 0,
down: 0
};
}
parents1.unshift(elem1);
}

// reset value of elem1 for use in the while loop that follows:
elem1 = parents1[parents1.length - 1];

// searches up the DOM from elem2 to the body, stopping and
// returning if it finds elem1 as a direct ancestor
while (elem2 !== document.body) {
elem2 = elem2.parentNode;
if (elem2 === elem1) {
return {
up: 0,
across: 0,
down: parents2.length
};
}
parents2.unshift(elem2);
}

// finds generation depth from body of first generation of ancestors
// of elem1 and elem2 that aren't common to both
while (parents1[gens] === parents2[gens]) {
gens++;
}

sibElem = parents1[gens];

// searches forward across siblings from the earliest non-common ancestor
// of elem1, looking for earliest non-common ancestor of elem2
while (sibElem) {
sibElem = sibElem.nextSibling;
if (sibElem && sibElem.tagName) {
sibs++;
if (sibElem === parents2[gens]) {
return {
up: parents1.length - gens - 1,
across: sibs,
down: parents2.length - gens - 1
};
}
}
}

sibs = 0;
sibElem = parents1[gens];

// searches backward across siblings from the earliest non-common ancestor
// of elem1, looking for earliest non-common ancestor of elem2
while (sibElem) {
sibElem = sibElem.previousSibling;
if (sibElem && sibElem.tagName) {
sibs--;
if (sibElem === parents2[gens]) {
return {
up: parents1.length - gens - 1,
across: sibs,
down: parents2.length - gens - 1
};
}
}
}

}

因此,例如,获取问题中描述的 DOM 中从 #div5#div10 的“距离”将使用如下内容:

var divOne = document.getElementById('div5'),
divTwo = document.getElementById('div10'),
distance = DOMdistance(divOne, divTwo);

因此距离将是:

{
up: 1,
across: 3,
down: 2
}

演示:http://jsfiddle.net/x58Ga/

关于javascript - DOM 中元素之间的“距离”(生成深度等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198994/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com