父子关系div移入移出 显示问题

父子关系div 移入移出 显示问题

要求移入box时,延迟显示 son,移出隐藏

<div id="box">
    <div id="son"></div>
</div>

<script>
var box = document.getElementById('box');
var big = document.getElementById('son');
var timmer;
box.onmouseover = big.onmouseover =function(){
    clearTimeout(timmer);
    big.style.display="block";
}
box.onmouseout= big.onmouseout =function(){
    timmer =setTimeout(function(){
    big.style.display="none";
    },300)
}
</script>

如果是这样的代码,会有一个问题,从 son 重新移入到 box时 子div还是会消失
所以重新写了测试的代码

<div id="box">
    <div id="son"></div>
</div>
<script>
    var box=document.getElementById('box');
    var son=document.getElementById('son');
    var timmer=null;
    box.onmouseover= function(){
        clearTimeout(timmer);
        son.style.display="block";
        console.log('父元素 移入');
    }
    son.onmouseover=function(){
        clearTimeout(timmer);
        son.style.display="block";
        console.log('子元素 移入');
    }
    son.onmouseout=function(){
        timmer = setTimeout(function () {
            son.style.display = "none";
        }, 300);
        console.log('子元素 移除');
    }
    box.onmouseout=function(){
        timmer= setTimeout(function() {
            son.style.display = "none";
        }, 300);
        console.log('父元素 移除');
    }
</script>

发现

这里写图片描述
最后从子元素移除,同时触发了父元素移除的 timmer定时器,所以产生了两个定时器,一次父元素移入的取消并不能行。发现问题的关键了,因为JS中的事件冒泡影响,所以在子元素移除事件中加一行取消冒泡即可

<div id="box">
    <div id="son"></div>
</div>
<script>
    var box = document.getElementById('box');
    var son = document.getElementById('son');
    var timmer = null;
    box.onmouseover = function () {
        clearTimeout(timmer);
        son.style.display = "block";
        console.log('父元素 移入');
    }
    son.onmouseover = function () {
        clearTimeout(timmer);
        son.style.display = "block";
        console.log('子元素 移入');
    }
    son.onmouseout = function (e) {
        timmer = setTimeout(function () {
            son.style.display = "none";
        }, 300);
        console.log('子元素 移除');
        var e = e || event; //兼容ie
        e.stopPropagation(); //取消冒泡
    }
    box.onmouseout = function () {
        timmer = setTimeout(function () {
            son.style.display = "none";
        }, 300);
        console.log('父元素 移除');
    }

这里写图片描述

这样就不会再出现上述问题了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值