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)
是的,有点.引入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的兼容性.(这有点难看:它使用了两个非标准的功能部分: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';
};
Run Code Online (Sandbox Code Playgroud)