是DOM中另一个元素之前或之后的元素

mrt*_*man 10 javascript jquery

有没有办法检测元素是否出现在标记中的另一个元素之前或之后?这与DOM中的位置无关.它可以是孩子,兄弟姐妹,父母或父母的父母.这是一个普遍的问题,所以没有标记要分享.

澄清 - 这是关于元素在标记中的位置,而不是它的显示位置.现在我想到了我的问题有点奇怪,因为如果你有元素X和元素Y那么你可以有这些场景.

//in regards to y
<x />
<y /> //:after

<y /> //:before
<x />

<x><y /></x> //not really before or after is it?
Run Code Online (Sandbox Code Playgroud)

lon*_*day 8

是的,有点.引入DOM3 Node.compareDocumentPosition,它允许您比较两个元素的位置.功能不是很友好:它涉及到bitmasks:这是一个简化其使用的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';
};
Run Code Online (Sandbox Code Playgroud)

此外,包含另一个元素的元素被认为在结构中位于其之前.


好吧,一个小小的谷歌搜索给了我这篇由John Resig(jQuery的创建者)撰写的博客文章,其中包括与IE <9的兼容性.(这有点难看:它使用了两个非标准的功能部分:containssourceIndex.)这段代码应该是跨浏览器的:

$.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';
};
Run Code Online (Sandbox Code Playgroud)


amo*_*era 7

node.compareDocumentPosition

摘要
比较当前节点与任何其他文档中另一个节点的位置.

更新:这不适用于所有浏览器,但有一个修复程序.感谢Alnitak(请参阅答案评论)提供链接:跨浏览器比较文档位置