美文网首页JS闯关之路
冒泡的几个问题

冒泡的几个问题

作者: icessun | 来源:发表于2017-07-28 22:04 被阅读1次

购物车问题

购物车与商品列表之间的切换,如何处理之间的冒泡问题。e.fromElemente.relatedTargetcontains()

<a href="javascript:;">
    <div></div>
</a>

<script>
    var oA=document.getElementsByTagName('a')[0];
    var oDiv=document.getElementsByTagName('div')[0];
    oA.onmouseover=function(e){
        e=e||window.event;
        // 获取到与oA有关的元素
        var oTo=e.fromElement||e.relatedTarget;
        //  如果oA包含了有关系的元素的时候,什么也不做;
        if(this.contains(oTo))  return;
        oDiv.style.display='block';
     };

    oA.onmouseout=function(e){
        var e=e||window.event;
        var oTo= e.toElement|| e.relatedTarget;
        if(this.contains(oTo)) return;
        oDiv.style.display='none';
   }

鼠标跟随问题

  • 这样写会出现当鼠标移动到里面的div时,出现闪动的现象
<div id="wrap">

</div>
<script>
    var oWrap=document.getElementById('wrap');
    var oS=null;
    oWrap.onmouseover=function(){
        oS=document.createElement('p');
        //当鼠标移入绿色div的时候,触发了绿色div的onmouseover事件,冒泡到父级oWrap.onmouseover
        oS.onmouseover=function(e){
            e=e||window.event;
            //阻止冒泡
            e.stopPropagation? e.stopPropagation(): e.cancelBubble=true;
        };
        this.appendChild(oS);
    };
    oWrap.onmousemove=function(e){
        e=e||window.event;
        oS.style.left= e.clientX-oWrap.offsetLeft+'px';
        oS.style.top= e.clientY-oWrap.offsetTop+'px';
    };
    oWrap.onmouseout=function(){
        oS.onmouseout=function(e){
            e=e||window.event;
            e.stopPropagation? e.stopPropagation(): e.cancelBubble=true;
        };
        this.removeChild(oS);
    }
  • 解决办法一
   oWrap.onmouseenter=function(){
        oS=document.createElement('p');
        this.appendChild(oS);
    };
    oWrap.onmousemove=function(e){
        e=e||window.event;
        oS.style.left= e.clientX-this.offsetLeft+'px';
        oS.style.top= e.clientY-this.offsetTop+'px';
    };
    oWrap.onmouseleave=function(){
        this.removeChild(oS);
    } 
  • 解决办法二
 oWrap.onmouseover=function(e){
        e=e||window.event;
        //oTo拿到的是跟oWrap有关系的元素;
        var oTo= e.fromElement|| e.relatedTarget;
        //如果oWrap包含了有关系的元素的时候,我们什么也不做;
        if(this.contains(oTo)) return;
        oS=document.createElement('p');
        this.appendChild(oS);
    };
    oWrap.onmousemove=function(e){
        e=e||window.event;
        oS.style.left= e.clientX-this.offsetLeft+'px';
        oS.style.top= e.clientY-this.offsetTop+'px';
    };
    oWrap.onmouseout=function(e){
        e=e||window.event;
        var oTo= e.toElement|| e.relatedTarget;
        if(this.contains(oTo)) return;
        this.removeChild(oS);
    }

相关文章

网友评论

    本文标题:冒泡的几个问题

    本文链接:https://www.haomeiwen.com/subject/cvaflxtx.html