爲非IE瀏覽器添加mouseenter,mouseleave事件

http://www.cnblogs.com/snandy/archive/2011/03/28/1997414.html

先了解幾個事件對象屬性

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不會觸發。如下

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8">
	<title>mouseerter與mouseover區別(IE下測試)</title>
</head>
<body>	
<div id="result" style="position:absolute;right:100px;top:5px;width:250px;height:400px;border:2px solid gray;overflow:auto;">	
</div>
<h3>1,鼠標在div[id=parent1]內部移動時會觸發mouseover事件</h3>
<div id="parent1" style="width:400px;border:1px solid gray;padding:5px;">
	<div id="child11" style="width:100px;height:100px;background:gold;float:left;">Child11</div>
	<div id="child12" style="width:100px;height:100px;background:gold;float:right;">Child12</div>
	<div style="clear:both;"></div>
</div>
<br/>
<h3>2,鼠標在div[id=parent2]內部移動時不會觸發mouseenter事件</h3>
<div id="parent2" style="width:400px;border:1px solid gray;padding:5px;">
	<div id="child21" style="width:100px;height:100px;background:gold;float:left;">Child21</div>
	<div id="child22" style="width:100px;height:100px;background:gold;float:right;">Child22</div>
	<div style="clear:both;"></div>
</div>

<script type="text/javascript">
	function on(el,type,fn){
		el.addEventListener ? el.addEventListener(type, fn, false) : el.attachEvent('on' + type, fn);
	}
	function $(id){
		return document.getElementById(id);
	}
	var p1 = $('parent1'),
		p2 = $('parent2');
	function fn(e){
		var d = document.createElement('div');
		d.innerHTML = e.type;
		$('result').appendChild(d);
	}
	on(p1,'mouseover',fn);
	on(p2,'mouseenter',fn);
</script>
<body>
</html>

瞭解了這三個屬性的意義後,實現起來就很簡單

E = function(){
   function elContains(a, b){
		try{
			return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition(b) & 16);
		}catch(e){}
		
   }
	function addEvt(el, type, fn){
		function fun(e){
			var a = e.currentTarget, b = e.relatedTarget;
			if(!elContains(a, b) && a!=b){
				fn.call(e.currentTarget,e);
			}	
		}	
		if(el.addEventListener){
			if(type=='mouseenter'){					
				el.addEventListener('mouseover', fun, false);					
			}else if(type=='mouseleave'){
				el.addEventListener('mouseout', fun, false);
			}else{
				el.addEventListener(type, fn, false);
			}
		}else{
			el.attachEvent('on' + type, fn);
		}
	}	
	return {addEvt:addEvt};
}();


發佈了5 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章