有没有办法检测一个元素是出现在标记中另一个元素之前还是之后?这不管在 DOM 中的位置。它可以是 child 、 sibling 、 parent 或 parent 的 parent 。这是一个一般性问题,因此没有要分享的标记。
澄清一下——这是关于元素在标记中的位置,而不是它的显示位置。现在想想我的问题有点奇怪,因为如果你有元素 X 和元素 Y,那么你就会有这些场景。
//in regards to y
<x />
<y /> //:after
<y /> //:before
<x />
<x><y /></x> //not really before or after is it?
最佳答案
是的,有点。 DOM3 介绍 Node.compareDocumentPosition
,它允许您比较两个元素的位置。功能不是很友好:它涉及位掩码:这是一个应该简化其使用的 jQuery 插件。
此代码仅在 Firefox 9 和当前版本的 Chromium 上进行了测试。当然它不会在旧版本的 IE 中工作。
$.fn.docPosition = function(element) {
if (element.jquery) element = element[0];
var position = this[0].compareDocumentPosition(element);
if (position & 0x04) return 'after';
if (position & 0x02) return 'before';
};
此外,包含另一个元素的元素被认为在结构中位于它之前。
好的,稍微谷歌一下就可以得到 this blog post by John Resig (jQuery 的创建者),包括与 IE <9 的兼容性。 (有点难看:它使用了两个非标准的功能位:contains
和 sourceIndex
。)这段代码应该是跨浏览器的:
$.fn.docPosition = function (element) {
function comparePosition(a, b) {
return a.compareDocumentPosition ?
a.compareDocumentPosition(b) :
a.contains ?
(a != b && a.contains(b) && 16) +
(a != b && b.contains(a) && 8) +
(a.sourceIndex >= 0 && b.sourceIndex >= 0 ?
(a.sourceIndex < b.sourceIndex && 4) +
(a.sourceIndex > b.sourceIndex && 2) :
1)
+ 0 : 0;
}
if (element.jquery) element = element[0];
var position = comparePosition(this[0], element);
if (position & 0x04) return 'after';
if (position & 0x02) return 'before';
};
关于javascript - 元素是在 DOM 中另一个元素之前还是之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8902270/