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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值