js中自定义mouseenter、mouseleave的写法

首先说一下什么是mouseenter事件:

实际上就是鼠标从外面移到某个元素里面(触发了目标方法)后,鼠标再在里面移动不会重新触发目标方法。moueseleave同理。

本身ie系列浏览器是有onmouseenter这个事件定义的,但是firefox之类的浏览器没有这个,所以只能模拟。

以下提供完美模拟的方法:

//ele为目标元素,type为事件类型不用'on',func为事件响应函数
var addEvent=function(ele,type,func){
	if(window.document.all)	
		ele.attachEvent('on'+type,func);//ie系列直接添加执行
	else{//ff
		if(type==='mouseenter')
			ele.addEventListener('mouseover',this.withoutChildFunction(func),false);
		else if(type==='mouseleave')
			ele.addEventListener('mouseout',this.withoutChildFunction(func),false);
		else
			ele.addEventListener(type,func,false);		
	}
}
var withoutChildFunction=function(func){
	return function(e){
		var parent=e.relatedTarget;//上一响应mouseover/mouseout事件的元素
		while(parent!=this&&parent){//假如存在这个元素并且这个元素不等于目标元素(被赋予mouseenter事件的元素)
			try{
				parent=parent.parentNode;}//上一响应的元素开始往上寻找目标元素
			catch(e){
				break;
			}
 
		}
		if(parent!=this)//以mouseenter为例,假如找不到,表明当前事件触发点不在目标元素内
		func(e);//运行目标方法,否则不运行
	}
}
function $(id){
	return document.getElementById(id);
}
addEvent($('parent'),'mouseenter',function(e){alert(e.relatedTarget);aa(1)});
function aa(a,b){
	alert(a);
}

原理有点难理解,但是大家可以看到,实际上当你在目标元素内(以mouseenter为例)移动,实际上还是会触发mouseover事件,但可以通过判断元素位置来判断是否执行目标方法。

2 Responses to js中自定义mouseenter、mouseleave的写法... »

  1. Snow 评论 2010-02-09 00:34

    joe~ 你这里弄得真牛哦。

    回复

    Joe 回复 二月 9th, 2010 at 12:42

    终于被你发现了

    回复

Leave a Reply

Email address is not published

You should say a Chinese word to pass spam check. If you can not input Chinese, just copy 你好 and paste them into comment text box.