简单地说,我需要确定两个兄弟元素中的哪一个按 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(...( 来执行此操作,并在兄弟姐妹用完时上升一个级别,下面是一个示例:
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.
}