JavaScript 跨浏览器MouseEnter / Leave解决方案

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 跨浏览器MouseEnter / Leave解决方案相关的知识,希望对你有一定的参考价值。

//since mouseenter & mouseleave are only supported in IE, this object helps to
// determine if the mouse is entering or leaving an element
//landmark: did the mouse enter or leave this "landmark" element? Was the event fired from within this element?
//usage:   var mbc = new MouseBoundaryCrossing(mouse_event, landmark);
function MouseBoundaryCrossing(evt, landmark)
{
	evt = evt || window.event;
	
	var eventType = evt.type;
	
	this.inLandmark = false;
	this.leftLandmark = false;
	this.enteredLandmark = false;
	
	if(eventType == "mouseout")
	{
		this.toElement = evt.relatedTarget || evt.toElement;
		this.fromElement = evt.target || evt.srcElement;
	}
	else if(eventType == "mouseover")
	{
		this.toElement = evt.target || evt.srcElement;
		this.fromElement = evt.relatedTarget || evt.fromElement;
	}
	else throw (new Error("Event type \""+eventType+"\" is irrelevant"));	//irrelevant event type
	
	//target is unknown
	//this seems to happen on the mouseover event when the mouse is already inside the element when the page loads and
	// the mouse is moved: fromElement is undefined
	if(!this.toElement || !this.fromElement) throw (new Error("Event target(s) undefined"));
	
	//determine whether from-element is inside or outside of landmark (i.e., does tmpFrom == the landmark or the document?)
	var tmpFrom = this.fromElement;
	while(tmpFrom.nodeType == 1)	//while tmpFrom is an element node
	{
		if(tmpFrom == landmark) break;
		tmpFrom = tmpFrom.parentNode;
	}
	
	//determine whether to-element is inside or outside of landmark (i.e., does tmpTo == the landmark or the document?)
	var tmpTo = this.toElement;
	while(tmpTo.nodeType == 1)	//while tmpTo is an element node
	{
		if(tmpTo == landmark) break;
		tmpTo = tmpTo.parentNode;
	}
	
	if(tmpFrom == landmark && tmpTo == landmark) this.inLandmark = true;	//mouse is inside landmark; didn't enter or leave
	else if(tmpFrom == landmark && tmpTo != landmark)	//mouse left landmark
	{
		this.leftLandmark = true;
		this.inLandmark = (eventType == "mouseout");	//mouseout: currently inside landmark, but leaving now
														//mouseover: currently outside of landmark; just left
	}
	else if(tmpFrom != landmark && tmpTo == landmark)	//mouse entered landmark
	{
		this.enteredLandmark = true;
		this.inLandmark = (eventType == "mouseover");	//mouseover: currently inside landmark; just entered
														//mouseout: currently outside of landmark, but entering now
	}
	//else	//mouse is outside of landmark; didn't enter or leave
}

以上是关于JavaScript 跨浏览器MouseEnter / Leave解决方案的主要内容,如果未能解决你的问题,请参考以下文章

跨浏览器鼠标输入/离开解决方案

JavaScript MouseEnter / Leave处理程序

JavaScript 原型自定义事件mouseenter mouseleave实现

javascript----mouseover和mouseenter的区别

JavaScript里mouseenter和mouseleave与mouseover和mouseout的区别

封装常用的Javascript跨浏览器方法