【发布时间】:2026-01-16 10:00:02
【问题描述】:
我想实现 compareDocumentPosition。 Resig 发了一个great start at doing just this。我已经把他的代码整理好了
function compareDocumentPosition(other) {
var ret = 0;
if (this.contains) {
if (this !== other && this.contains(other)) {
ret += 16;
}
if (this !== other && other.contains(this)) {
ret += 8;
}
if (this.sourceIndex >= 0 && other.sourceIndex >= 0) {
if (this.sourceIndex < other.sourceIndex) {
ret += 4;
}
if (this.sourceIndex > other.sourceIndex) {
ret += 2;
}
} else {
ret += 1;
}
}
return ret;
}
这适用于Element,但不适用于Text 或DocumentFragment。这是因为 IE8 没有在这些节点上提供.sourceIndex。 (它也不给.contains,但我已经解决了这个问题)
如何有效地编写对应于DOCUMENT_POSITION_FOLLOWING 和DOCUMENT_POSITION_PRECEDING 的+=4 和+=2 位。
作为额外参考,这两个由 DOM4 定义的树顺序定义
如果 A 和 B 在同一棵树中并且 A 在树顺序中位于 B 之前,则对象 A 在对象 B 之前。
如果 A 和 B 在同一棵树中,并且 A 按树顺序在 B 之后,则对象 A 跟随对象 B。
树的顺序是前序,深度优先遍历。
大多数现代浏览器都实现了这一点(包括 IE9)。所以你只需要在 IE8 中工作的东西(我不关心 IE6/7,但如果它工作得很好!)
【问题讨论】:
标签: javascript internet-explorer-8 shim dom4