zoukankan      html  css  js  c++  java
  • onmouseover和onmouseout的烦恼

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

     

    非常easy的逻辑,这也是我们想要的!但随之烦恼也就来了: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事件中指向鼠标去往的那个元素
  • 相关阅读:
    n皇后问题
    POJ2155 Matrix二维线段树经典题
    hiho一下 第六十六周
    hdu1754 I hate it线段树模板 区间最值查询
    hdu5481 Desiderium
    自增运算符
    hdu-1823 Luck and Love
    Oracle 函数大全
    对前台传过来的实体是否为空 进行为空校验的N种方法
    IOC和DI的区别详解
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/3910945.html
Copyright © 2011-2022 走看看