情况一:当鼠标移入(onmouseover)父级p(红色)时,子p(蓝色)显示(黑点代表鼠标);
情况二:当子p(蓝色)处于显示状态时,把鼠标移动到上面。此时鼠标已经脱离父p(红色),但子p仍然显示。白色代表鼠标移动轨迹。
请问为什么鼠标移出父p(红色)时,为什么子p还能显示(蓝色)?这种表现背后的工作原理是什么样的呢?
<!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;}
/*设置父p的样式:宽、高、行高、相对定位、背景、边框*/
.father{width:300px;height:40px;line-height:40px;
position:relative;left:0;top:0;
background:#F60;
border:3px dotted #ccc;
}
/*设置子p的样式:宽、高、背景、绝对定位,display:none*/
.son{width:130px;height:160px;
background:aqua;font-weight:bold;
position:absolute;left:0;top:40px;
display:none;
}
</style>
</head>
<body>
<p class="father" id="father">
<p class="son" id="son">绝对定位</p>
</p>
<script>
/*获取父p和子p*/
var father=document.getElementById('father');
var son=document.getElementById('son');
/*鼠标移入父p时,显示子p*/
father.onmouseover=function(){
son.style.display='block';
};
/*鼠标移出父p时,显示子p*/
father.onmouseout=function(){
son.style.display='none';
};
</script>
</body>
</html>
确实是事件冒泡的原因,如果你对这个不熟悉的话,这里有一篇文章可以看看生动详细解释javascript的冒泡和捕获,包懂包会
对你的js代码稍作修改如下:
事件冒泡概括来讲就是,在一个
dom
树中,如果移入了son
这个dom
,那么移入事件会一直冒泡,也就是说会触发son
及所有son
祖先元素的移入事件。你可以按我的代码测试下你的路径,这样可能会体会更深。如果你想让你移入
son
时不触发father
的移入时间,可以取消冒泡,像如下这样在son
中添加一句ev.cancelBubble=true
即可。son 也属于 father
segmentfault我还不太会用,在这里感谢所有帮我解答问题的朋友,谢谢你们的热心帮助。