Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:因为事件主体与事件目标之间并非父子关系 , 还有中间层,冒泡的影响, 这些不理解 就先放放吧, 不着急
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- 引入外部css样式文件 -->
<link rel="stylesheet" href="css/style.css" />
<title>css定位</title>
</head>
<body>
<div class="navbox">
<ul id="navid">
<li><a href="javascript:void(0)">菜单一</a></li>
<li><a href="javascript:void(0)">菜单二</a></li>
<li><a href="javascript:void(0)">菜单三</a></li>
<li><a href="javascript:void(0)">菜单四</a></li>
<li>
<a href="javascript:void(0)">更多菜单一</a>
<div class="nav-item-box">
<div class="nav-item">子菜单1</div>
<div class="nav-item">子菜单2</div>
<div class="nav-item">子菜单3</div>
</div>
</li>
<li>
<a href="javascript:void(0)">更多菜单二</a>
<div class="nav-item-box">
<div class="nav-item">子菜单4</div>
<div class="nav-item">子菜单5</div>
<div class="nav-item">子菜单6</div>
</div>
</li>
</ul>
</div>
</body>
<script type="text/javascript">
let navbox = document.querySelectorAll(".navbox>ul li");
navbox.forEach(function (li) {
//给一级菜单增加监听事件
li.addEventListener("mouseover", mouseoverFun); //鼠标移动事件
li.addEventListener("mouseout", mouseoutFun); //鼠标移出事件
});
function mouseoverFun(e) {
//判断是否存在子菜单,存在就显示
if (e.target.nextElementSibling != null) {
e.target.nextElementSibling.style.display = "block";
}
}
function mouseoutFun(e) {
console.log(e);
//判断是否存在子菜单,存在就隐藏
if (e.target.nodeName === "A" && e.target.nextElementSibling != null) {
e.target.nextElementSibling.style.display = "none";
}
}
</script>
</html>
* {
padding: 0;
margin: 0;
}
a {
text-decoration: none; /*去掉a标签下划线*/
}
.navbox {
height: 60px;
line-height: 60px; /*块级元素中,垂直居中*/
width: 100%;
background: #000000;
}
.navbox ul li {
position: relative;
list-style: none; /*去掉li前面小黑点*/
float: left;
font-size: 14px;
}
.navbox ul li a {
color: rgba(255, 255, 255, 0.7);/*a标签颜色,最后0.7表示透明度*/
padding: 0 30px;
}
/* 子菜单样式 */
.navbox ul li .nav-item-box {
position: absolute;/*相对最近relative,绝对定位*/
top: 60px;
left: 0;
right: 0;
display: none;
}
.navbox ul li .nav-item-box .nav-item {
height: 35px;
line-height: 35px;
padding: 0 30px;
}
1.理解了js冒泡(由内向外传递,addEventListener(事件类型,事件方法,false),最后一个参数默认false,可以省略;
2.理解了js捕获穿透(由外向内传递,addEventListener(事件类型,事件方法,true));
3.问题:鼠标移出导航a标签,下面下拉导航就被隐藏,就用上面js方法进行处理,没有思路