创建兼容 IE/FireFox 的 event 及 event 的 srcElement、fromElement、toElement 属性

自然,我们都习惯了 IE,在 IE 中要在函数中获得各事件对象很容易,直接用 event、event.srcElemtn、event.fromElement、event.toElement 就行了。在 FireFox 中获得触发事件的元素可以用 event.target,但其他两个 fromElement 和 toElement 就要费些周折。

所以,为了保持一致的使用方式,也为了保持原有的使用习惯,我们加入以下 JS 代码(代码有些紧凑,未加注释,应该很好理解):
 1<script language="javascript">
 2
 3  if(window.addEventListener) { FixPrototypeForGecko(); }
 4
 5  function  FixPrototypeForGecko()
 6  {
 7      HTMLElement.prototype.__defineGetter__("runtimeStyle",element_prototype_get_runtimeStyle);
 8      window.constructor.prototype.__defineGetter__("event",window_prototype_get_event);
 9      Event.prototype.__defineGetter__("srcElement",event_prototype_get_srcElement);
10      Event.prototype.__defineGetter__("fromElement",  element_prototype_get_fromElement);
11      Event.prototype.__defineGetter__("toElement", element_prototype_get_toElement);
12
13  }
14
15  function  element_prototype_get_runtimeStyle() { return  this.style; }
16  function  window_prototype_get_event() { return  SearchEvent(); }
17  function  event_prototype_get_srcElement() { return  this.target; }
18
19  function element_prototype_get_fromElement() {
20      var node;
21      if(this.type == "mouseover") node = this.relatedTarget;
22      else if (this.type == "mouseout") node = this.target;
23      if(!node) return;
24      while (node.nodeType != 1)
25          node = node.parentNode;
26      return node;
27  }
28
29  function  element_prototype_get_toElement() {
30          var node;
31          if(this.type == "mouseout")  node = this.relatedTarget;
32          else if (this.type == "mouseover") node = this.target;
33          if(!node) return;
34          while (node.nodeType != 1)
35             node = node.parentNode;
36          return node;
37  }
38
39  function  SearchEvent()
40  {
41      if(document.all) return  window.event;
42
43      func = SearchEvent.caller;
44
45      while(func!=null){
46          var  arg0=func.arguments[0];
47
48          if(arg0 instanceof Event) {
49              return  arg0;
50          }
51         func=func.caller;
52      }
53      return   null;
54  }
55</script>

好了,现在不管是在 IE 中还是在 FireFox 中,触发事件后都有了 event、event.srcElement、event.fromElement、event.toElement 属性了。这就来做个测试吧:
1<script>
2  function test(){
3      alert("event:" + event +", srcElement:"+event.srcElement.innerHTML+
4        ", fromElement:"+event.fromElement.innerHTML + ", toElement:"+event.toElement.innerHTML)
5  }
6</script><br/><br/>
7<button onmouseout="test()">MouseOut</button><button onmouseover="test()">MouseOver</button>

页面中有两个按钮 MouseOut 和 MouseOver,你掠过第一个按钮到第二个按钮上是,有看到这样内容的窗口:


从上图可以看出,其实我是在 Google 的 Chrome 浏览器中作的测试,也是有效的。标题虽说是兼容 IE 和 FireFox,但宽松点说就是 IE  和非 IE,因为 IE 总喜欢剑起偏锋,不按规范办事,不过这种事在 IE 8 中是收敛了许多。

永久链接 https://yanbin.blog/ie-firefox-event-srcelement-fromelement-toelement/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。