请看http://xuganggogo.iteye.com/admin/blogs/538476,有更简单解决方案。
在FireFox下,处理onMouseOut() 经过子元素也触发的问题与IE下大不相同,而且步骤比较多。
1,首先FF不支持,event.toElement 和 event.formElement , 但是我们可以自己让FF支持,如下
//创建兼容 IE/FireFox 的 event 及 event 的 srcElement、fromElement、toElement 属性----start function FixPrototypeForGecko() { HTMLElement.prototype.__defineGetter__("runtimeStyle",element_prototype_get_runtimeStyle); window.constructor.prototype.__defineGetter__("event",window_prototype_get_event); Event.prototype.__defineGetter__("srcElement",event_prototype_get_srcElement); Event.prototype.__defineGetter__("fromElement", element_prototype_get_fromElement); Event.prototype.__defineGetter__("toElement", element_prototype_get_toElement); } function element_prototype_get_runtimeStyle() { return this.style; } function window_prototype_get_event() { return SearchEvent(); } function event_prototype_get_srcElement() { return this.target; } function element_prototype_get_fromElement() { var node; if(this.type == "mouseover") node = this.relatedTarget; else if (this.type == "mouseout") node = this.target; if(!node) return; while (node.nodeType != 1) node = node.parentNode; return node; } function element_prototype_get_toElement() { var node; if(this.type == "mouseout") node = this.relatedTarget; else if (this.type == "mouseover") node = this.target; if(!node) return; while (node.nodeType != 1) node = node.parentNode; return node; } function SearchEvent() { if(document.all) return window.event; func = SearchEvent.caller; while(func!=null){ var arg0=func.arguments[0]; if(arg0 instanceof Event) { return arg0; } func=func.caller; } return null; }
2,FF不支持contains方法,但是有compareDocumentPosition方法。
function mouseoutIM( evt ){ var res= evt.compareDocumentPosition(event.toElement) ; if( ! ( res == 20 || res == 0) ){ alert('ok'); } } }
3,compareDocumentPosition()方法说明
NodeA.compareDocumentPosition(NodeB)
这个方法是 DOM Level 3 specification 的一部分,允许你确定 2 个 DOM Node 之间的相互位置。这个方法比 .contains() 强大。这个方法的一个可能应用是排序 DOM Node 成一个详细精确的顺序。
使用这个方法你可以确定关于一个元素位置的一连串的信息。所有的这些信息将返回一个比特码(Bit,比特,亦称二进制位)。
对于那些,人们知之甚少。比特码是将多重数据存储为一个简单的数字(译者注:0 或 1)。你最终打开 / 关闭个别数目(译者注:打开/关闭对应 0 /1),将给你一个最终的结果。
这里是从 NodeA.compareDocumentPosition(NodeB) 返回的结果,包含你可以得到的信息。
Bits Number Meaning 000000 0 元素一致 000001 1 节点在不同的文档(或者一个在文档之外) 000010 2 节点 B 在节点 A 之前 000100 4 节点 A 在节点 B 之前 001000 8 节点 B 包含节点 A 010000 16 节点 A 包含节点 B 100000 32 浏览器的私有使用 |
现在,这意味着一个可能的结果类似于:
<div id="a"> <div id="b"></div> </div> <script> alert( document.getElementById("a").compareDocumentPosition(document.getElementById("b")) == 20); </script> |
一旦一个节点 A 包含另一个节点 B,包含 B(+16) 且在 B 之前(+4),则最后的结果是数字 20 。如果你查看比特发生的变化,将增加你的理解。
000100 (4) + 010000 (16) = 010100 (20)
这个,毫无疑问,有助于理解单个最混乱的 DOM API 方法。当然,他的价值当之无愧的。