简单地说,我需要确定两个兄弟元素中哪一个在 DOM 顺序中排在第一位,但它们可能不是直接相邻的兄弟元素。我当前用于执行此操作的代码如下所示:
/**
* Determine if an element comes before or after another element.
*
* This requires both elements to be siblings.
*
* @param {Element} el1 - The element to use as a reference.
* @param {Element} el2 - The element to look for.
* @returns {?boolean} True if el2 comes before el1, false if el1 comes before el2, undefined otherwise.
*/
function isBefore(el1, el2) {
let tmp = el1
while (tmp.previousElementSibling) {
if (tmp.previousElementSibling === el2) {
return true
}
tmp = tmp.previousElementSibling
}
tmp = el1.nextElementSibling
while (tmp.nextElementSibling) {
if (tmp.nextElementSibling === el2) {
return false
}
tmp = tmp.nextElementSibling
}
return undefined
}
我想知道是否有一些更有效的方法可以在普通 JavaScript 中执行此检查。
最佳答案
您可以使用 contains(...) 来执行此操作当你的 sibling 用完时就升一级,这是一个例子:
function isBefore(el1, el2) {
if (el1.contains(el2) || el2.contains(el1)) {
return undefined; // not before or after, it's a parent child relationship.
}
let tmp = el1.previousElementSibling || el1.parentElement
while (tmp) {
if (tmp === el2 || tmp.contains(el2)) {
return true
}
tmp = tmp.previousElementSibling || tmp.parentElement;
}
return false; // if it is not before, it must be after.
}
关于javascript - 如何使用 Javascript 有效地确定 HTML 文档中同级元素的相对顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57379579/