`
Anddy
  • 浏览: 192683 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

javascript Events

阅读更多

项目中需要用到弹出层,显示蛋白质序列的详细信息:

鼠标在链接上面,弹出另外一个层,层内显示详细,鼠标离开时,弹出层消失。

问题看似简单,做起来问题渐显。

再次真正理解js中event事件。

 

下面文章讲的让人拍案叫绝,拿出来分享分享

 

http://www.quirksmode.org/js/events_mouse.html

 

Mousing out of a layer

--------------
| Layer         |.onmouseout = doSomething;
| --------       |
| | Link | -------> We want to know about this mouseout
| |        |       |
| --------        |
| --------        |
| | Link |       |
| |    ---->     | but not about this one
| --------        |
--------------
---->: mouse movement
function doSomething(e) {
	if (!e) var e = window.event;
	var tg = (e.srcElement) ? e.srcElement : e.target;
	if (tg.nodeName != 'DIV') return;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	while (reltg != tg && reltg.nodeName != 'BODY')
		reltg= reltg.parentNode
	if (reltg== tg) return;
	// Mouseout took place when mouse actually left layer
	// Handle event
}

在应用时,注意while循环中条件的判定!视不同的情况

文章解释

Explanation
First get the event target, ie. the element the mouse moved out of. If the target is not the DIV (layer), end the function immediately, since the mouse has certainly not left the layer.

If the target is the layer, we're still not sure if the mouse left the layer or entered a link within the layer. Therefore we're going to check the relatedTarget/toElement of the event, ie. the element the mouse moved to.

We read out this element, and then we're going to move upwards through the DOM tree until we either encounter the target of the event (ie. the DIV), or the body element.

If we encounter the target the mouse moves towards a child element of the layer, so the mouse has not actually left the layer. We stop the function.

When the function has survived all these checks we're certain that the mouse has actually left the layer and we can take appropriate action (usually making the layer invisible).
 
fromElement toElement relatedTarget target srcElement
Mouseover
function doSomething(e) {
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.fromElement;
}

 
Mouseout
function doSomething(e) {
	if (!e) var e = window.event;
	var relTarg = e.relatedTarget || e.toElement;
}
 

Mousemove

element.onmousemove = doSomething;
// later
element.onmousemove = null;
 
Expanation
Therefore it’s best to register an onmousemove event handler only when you need it and to remove it as soon as it’s not needed any more:
 
the article is perfect ! thx
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics