是DOM中另一个元素之前或之后的元素 [英] Is element before or after another element in DOM

查看:344
本文介绍了是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引入了 Node.compareDocumentPosition ,它允许您比较两个元素的位置。功能不是很友好:它涉及到bitmasks:这是一个jQuery插件,可以简化其使用。

Yes, sort of. DOM3 introduced Node.compareDocumentPosition, which allows you to compare the position of two elements. The functionality isn't very friendly: it involves bitmasks: this is a jQuery plugin that should simplify its use.

此代码仅在Firefox 9和当前版本上测试铬。当然它不适用于旧版本的IE。

This code is only tested on Firefox 9 and the current version of Chromium. Certainly it won't work in old versions of 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';
};

此外,包含另一个元素的元素在结构中被认为是在它之前。

Also, an element that contains another is considered to be before it in the structure.

好的,有点Google搜索给了我这篇由John Resig发表的博客(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中另一个元素之前或之后的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆