gpt4 book ai didi

javascript - 跨浏览器比较文档位置

转载 作者:数据小太阳 更新时间:2023-10-29 05:08:41 27 4
gpt4 key购买 nike

DOM4 compareDocumentPosition

我想实现 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 但不适用于 TextDocumentFragment。这是因为 IE8 不会在这些节点上提供 .sourceIndex。 (它也不提供 .contains 但我已经解决了这个问题)

我如何有效地编写对应于 DOCUMENT_POSITION_FOLLOWING+=4+=2 位?和 DOCUMENT_POSITION_PRECEDING .

作为额外引用,这两个由 DOM4 定义的树序定义

An object A is preceding an object B if A and B are in the same tree and A comes before B in tree order.

An object A is following an object B if A and B are in the same tree and A comes after B in tree order.

The tree order is preorder, depth-first traversal.

大多数现代浏览器都实现了这一点(包括 IE9)。所以你只需要在 IE8 中工作的东西(我不关心 IE6/7,但如果它工作得很棒!)

最佳答案

function recursivelyWalk(nodes, cb) {
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
var ret = cb(node);
if (ret) {
return ret;
}
if (node.childNodes && node.childNodes.length) {
var ret = recursivelyWalk(node.childNodes, cb);
if (ret) {
return ret;
}
}
}
}

function testNodeForComparePosition(node, other) {
if (node === other) {
return true;
}
}

function compareDocumentPosition(other) {
function identifyWhichIsFirst(node) {
if (node === other) {
return "other";
} else if (node === reference) {
return "reference";
}
}

var reference = this,
referenceTop = this,
otherTop = other;

if (this === other) {
return 0;
}
while (referenceTop.parentNode) {
referenceTop = referenceTop.parentNode;
}
while (otherTop.parentNode) {
otherTop = otherTop.parentNode;
}

if (referenceTop !== otherTop) {
return Node.DOCUMENT_POSITION_DISCONNECTED;
}

var children = reference.childNodes;
var ret = recursivelyWalk(
children,
testNodeForComparePosition.bind(null, other)
);
if (ret) {
return Node.DOCUMENT_POSITION_CONTAINED_BY +
Node.DOCUMENT_POSITION_FOLLOWING;
}

var children = other.childNodes;
var ret = recursivelyWalk(
children,
testNodeForComparePosition.bind(null, reference)
);
if (ret) {
return Node.DOCUMENT_POSITION_CONTAINS +
Node.DOCUMENT_POSITION_PRECEDING;
}

var ret = recursivelyWalk(
[referenceTop],
identifyWhichIsFirst
);
if (ret === "other") {
return Node.DOCUMENT_POSITION_PRECEDING;
} else {
return Node.DOCUMENT_POSITION_FOLLOWING;
}
}

我自己写的。我认为这个实现有问题,但它是我的其他一些代码中的错误。看起来很结实。

关于javascript - 跨浏览器比较文档位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8334286/

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