本文介绍了是DOM中另一个元素之前或之后的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

Is there a means of detecting whether an element appears before or after another element in markup? This is regardless of position in DOM. It could be a child, a sibling, a parent or a parent's parent. This is a general question, so no markup to share.

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

To clarify - this is in regards to the element's position in markup, not its display position. Now that I think about it my question is a bit strange because if you have element X and element Y then you can have these scenarios.

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

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

<x><y /></x> //not really before or after is it?


推荐答案

是的,有点儿。 DOM3引入了(jQuery的创建者),其中包括与IE< 9的兼容性。 (这有点难看:它使用两个非标准功能:包含 sourceIndex 。)此代码应该是跨浏览器:

OK, a little Googling gives me this blog post by John Resig (the creator of jQuery), which includes compatibility with IE <9. (It's a little ugly: it uses two non-standard bits of functionality: contains and sourceIndex.) This code should be cross-browser:

$.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';
};

这篇关于是DOM中另一个元素之前或之后的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:14