mouseover以及mouseout事件问题解决方案

来源:互联网 发布:淘宝购物有发票吗 编辑:程序博客网 时间:2024/05/16 08:28

mouseover事件:鼠标进入元素或者在元素内部游走时候触发该事件;

mouseout事件:鼠标离开该元素触发事件;

现在我们有一个div,div中包含一个span,需求需要在鼠标在div内部时候监听鼠标位置;即mouseover事件,

真正测试时候发现鼠标在进入span时候会触发mouseout事件然后再触发mouseover事件,一般情况下我们不会认为鼠标进入div内部的span就是离开该div了。

于是想办法解决如下:

整体思路:mouseout时候判断目标元素是否包含在div之内,如果不包含在div之内则触发该离开事件;同理,mouseover时候判断目标元素是否包含在div之内,如果包含的话则不触发mouseover事件,不包含则执行mouseout事件;

这里有两个点需要注意:一个是判断是否包含,另一个是判断目标元素;

第一个点:判断是否包含(即检测一个元素是否是另一个元素的父元素)

ie中有contains方法即ele.contains(childEle)而火狐等浏览器中没有这个方法但是提供了compareDocumentPosition方法即:refNode.compareDocumentPosition(otherNode);

我们介于此来封装一下ischildOf方法如下:

var zip_code={};

zip_code.isChildOf=function(refNode,otherNode){

if(typeof refNode.contains=='function'&&(!client.engine.webkit||client.engine.webkit>=522)){

       return refNode.contains(otherNode);

    }else if(typeof refNode.compareDocumentPosition=='function'){

        return !!(refNode.compareDocumentPosition(otherNode)&16);

   }else{

        var node=otherNode.parentNode;

        do{

           if(node===refNode){

                return true;

           }else{

                node=node.parentNode

           }

        }while (node!==null);

            return false;

      }

}

第二个点:判断目标元素(仅适用于mouseover以及mouseout事件)

DOM元素通过event对象的relatedTarget属性来判断目标元素,而ie中没有该属性,但是提供了fromElement以及toElement属性提供了相关信息去判断目标元素,封装如下:

zip_code.getRelatedTarget=function(event){

    if(event.relatedTarget){

        return event.relatedTarget;

    }

    else if(event.toElement){

        return event.toElement;

    }else if(event.fromElement){

        return event.fromElement

    }else {

        return null

    }

}

解决了上述两点之后我们对其应用来解决上述问题:

document.getElementById(div).onmouseout=function(e){
var e=e?e:window.event,target=e.target?e.target:e.srcElemet,relatedTag=zip_code.getRelatedTarget(e),isChild=zip_code.isChildOf(target,relatedTag);

if(!isChild){

 doxxfun()

}

}

上述代码在鼠标进入span时候判断目标元素relatedTag也就是span是否是div的子元素,如果是则不执行mouseout事件,如果不是则继续执行mouseout事件。

0 0
原创粉丝点击