首页 > 新人请教个dom操作的问题:鼠标移入/移出父div,子div显示/隐藏。但在鼠标移出父div时,子div却仍然显示?求解

新人请教个dom操作的问题:鼠标移入/移出父div,子div显示/隐藏。但在鼠标移出父div时,子div却仍然显示?求解

情况一:当鼠标移入(onmouseover)父级div(红色)时,子div(蓝色)显示(黑点代表鼠标);

情况二:当子div(蓝色)处于显示状态时,把鼠标移动到上面。此时鼠标已经脱离父div(红色),但子div仍然显示。白色代表鼠标移动轨迹。

请问为什么鼠标移出父div(红色)时,为什么子div还能显示(蓝色)?这种表现背后的工作原理是什么样的呢?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
*{margin:0;padding:0;}

/*设置父div的样式:宽、高、行高、相对定位、背景、边框*/
.father{width:300px;height:40px;line-height:40px;
    position:relative;left:0;top:0;
    background:#F60;
    border:3px dotted #ccc;
}

/*设置子div的样式:宽、高、背景、绝对定位,display:none*/
.son{width:130px;height:160px;
    background:aqua;font-weight:bold;
    position:absolute;left:0;top:40px;
    display:none;
}
</style>
</head>
<body>

    <div class="father" id="father">
        <div class="son" id="son">绝对定位</div>
    </div>


<script>
    /*获取父div和子div*/
    var father=document.getElementById('father');
    var son=document.getElementById('son');
    
    /*鼠标移入父div时,显示子div*/
    father.onmouseover=function(){
        son.style.display='block';
    };
    
    /*鼠标移出父div时,显示子div*/    
    father.onmouseout=function(){
        son.style.display='none';
    };  
</script>


</body>
</html>

son 也属于 father


我还不太会用,在这里感谢所有帮我解答问题的朋友,谢谢你们的热心帮助。


确实是事件冒泡的原因,如果你对这个不熟悉的话,这里有一篇文章可以看看生动详细解释javascript的冒泡和捕获,包懂包会
对你的js代码稍作修改如下:

/*获取父div和子div*/
    var father=document.getElementById('father');
    var son=document.getElementById('son');

    /*鼠标移入父div时,显示子div*/
    father.onmouseover=function(){
        alert('父级触发移入事件');
        son.style.display='block';
    };

    /*鼠标移出父div时,隐藏子div*/
    father.onmouseout=function(){
        alert('父级触发移出事件');
        son.style.display='none';
    };

    /*鼠标移入子div时*/
    son.onmouseover=function(){
        alert('子级触发移入事件');
    }

事件冒泡概括来讲就是,在一个dom树中,如果移入了son这个dom,那么移入事件会一直冒泡,也就是说会触发son及所有son祖先元素的移入事件。你可以按我的代码测试下你的路径,这样可能会体会更深。
如果你想让你移入son时不触发father的移入时间,可以取消冒泡,像如下这样在son中添加一句ev.cancelBubble=true即可。

 /*获取父div和子div*/
    var father=document.getElementById('father');
    var son=document.getElementById('son');

    /*鼠标移入父div时,显示子div*/
    father.onmouseover=function(){
        alert('父级触发移入事件');
        son.style.display='block';
    };

    /*鼠标移出父div时,隐藏子div*/
    father.onmouseout=function(){
        alert('父级触发移出事件');
        son.style.display='none';
    };

    /*鼠标移入子div时*/
    son.onmouseover=function(ev){
        alert('子级触发移入事件');
        ev.cancelBubble = true;
    }
【热门文章】
【热门文章】