在学习之前我们先了解几个事件对象属性:
target: 指事件源对象,点击嵌套元素最里层的某元素,该元素就是target。IE6/7/8对应的是srcElement。
currentTarget: 指添加事件handler的元素本身,如el.addEventListener中el就是currentTarget。IE6/7/8没有对应属性,可在handler内使用this来替代如evt.currentTarget = this。
relativeTarget: 指事件相关的元素,一般用在mouseover,mouseout事件中。IE6/7/8中对应的是fromElement,toElement。
mouseenter ,mouseleave IE9中仍然支持,mouseenter与mouseover区别在于:在元素内部移动时mouseenter不会触发。如下
view sourceprint?
01 <!DOCTYPE HTML>
02 <html>
03 <head>
04 <meta charset="utf-8">
05 <title>mouseerter与mouseover区别(IE下测试)</title>
06 </head>
07 <body>
08 <div id="result" style="position:absolute;right:100px;top:5px;width:250px;height:400px;border:2px solid gray;overflow:auto;">
09 </div>
10 <h3>1,鼠标在div[id=parent1]内部移动时也会触发mouseover事件</h3>
11 <div id="parent1" style="width:400px;border:1px solid gray;padding:5px;">
12 <div id="child11" style="width:100px;height:100px;background:gold;float:left;">Child11</div>
13 <div id="child12" style="width:100px;height:100px;background:gold;float:right;">Child12</div>
14 <div style="clear:both;"></div>
15 </div>
16 <br/>
17 <h3>2,鼠标在div[id=parent2]内部移动时也不会触发mouseenter事件</h3>
18 <div id="parent2" style="width:400px;border:1px solid gray;padding:5px;">
19 <div id="child21" style="width:100px;height:100px;background:gold;float:left;">Child21</div>
20 <div id="child22" style="width:100px;height:100px;background:gold;float:right;">Child22</div>
21 <div style="clear:both;"></div>
22 </div>
23
24 <script type="text/javascript">
25 function on(el,type,fn){
26 el.addEventListener ? el.addEventListener(type, fn, false) : el.attachEvent('on' + type, fn);
27 }
28 function $(id){
29 return document.getElementById(id);
30 }
31 var p1 = $('parent1'),
32 p2 = $('parent2');
33 function fn(e){
34 var d = document.createElement('div');
35 d.innerHTML = e.type;
36 $('result').appendChild(d);
37 }
38 on(p1,'mouseover',fn);
39 on(p2,'mouseenter',fn);
40 </script>
41 <body>
42 </html>
了解了这三个属性的意义后,实现起来就很简单
view sourceprint?01 E = function(){
02 function elContains(a, b){
03 try{
04 return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition(b) & 16);
05 }catch(e){}
06
07 }
08 function addEvt(el, type, fn){
09 function fun(e){
10 var a = e.currentTarget, b = e.relatedTarget;
11 if(!elContains(a, b) && a!=b){
12 fn.call(e.currentTarget,e);
13 }
14 }
15 if(el.addEventListener){
16 if(type=='mouseenter'){
17 el.addEventListener('mouseover', fun, false);
18 }else if(type=='mouseleave'){
19 el.addEventListener('mouseout', fun, false);
20 }else{
21 el.addEventListener(type, fn, false);
22 }
23 }else{
24 el.attachEvent('on' + type, fn);
25 }
26 }
27 return {addEvt:addEvt};
28 }();