onmouseover和onmouseout的烦恼

一个DIV层,当鼠标移进的时候会触发onmouseover,移出的时候会触发onmouseout。

 

很简单的逻辑,这也是我们想要的!但随之烦恼也就来了:onmouseover并不会只在移进时才触发,onmouseout也不会只在移出时才触发!鼠标在DIV里面移动时也会可能触发onmouseover或onmouseout。

 

在上图中,对于’A'来说:当鼠标进入’A'(路径’1′)时那么就会触发’A'的onmouseover事件;接着鼠标移动到’B'(路径’2′),此时’A'会触发onmouseout(先)和onmouseover(后)事件。

由此可见,如果HTML元素(‘A’层)内还有其他元素(‘B’,'C’层),当我们移动到这些内部的元素时就会触发最外层(‘A’层)的onmouseout和onmouseover事件。

这两个事件的触发表现真的就是你想要的吗?也许你需要一个只在移进时才触发的,一个只在移出时才触发的事件,不管其内部是否还有其他元素….

 

解决方案

在IE下确实有你需要的两个这样事件:onmouseenter 和 onmouseleave。但很不幸FF等其他浏览器并不支持,只好模拟实现:

document.getElementById('...').onmouseover = function(e){
    if( !e ) e = window.event;
    var reltg = e.relatedTarget ? e.relatedTarget : e.fromElement;
    while( reltg && reltg != this ) reltg = reltg.parentNode;
    if( reltg != this ){
        // 这里可以编写 onmouseenter 事件的处理代码
    }
}

 

document.getElementById('...').onmouseout = function(e){
    if( !e ) e = window.event;
    var reltg = e.relatedTarget ? e.relatedTarget : e.toElement;
    while( reltg && reltg != this ) reltg = reltg.parentNode;
    if( reltg != this ){
        // 这里可以编写 onmouseleave 事件的处理代码
   }
}


 

 

备注:

W3C在mouseover和mouseout事件中添加了relatedTarget属性

  • 在mouseover事件中,它表示鼠标来自哪个元素
  • 在mouseout事件中,它指向鼠标去往的那个元素

而Microsoft在mouseover和mouseout事件中添加了两个属性

  • fromElement,在mouseover事件中表示鼠标来自哪个元素
  • toElement,在mouseout事件中指向鼠标去往的那个元素
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值