这样写好像也可以,但是不太懂underline是怎么改变位置的
来源:2-8 项目作业
DanielDu87
2023-01-31 23:34:41
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>document</title>
</head>
<style>
* {
font-size: 16px;
margin: 0;
padding: 0;
}
.box {
position: relative;
width: 710px;
height: 50px;
margin: 30px auto;
background-color: orange;
}
.box h2 {
line-height: 30px;
display: inline-block;
float: left;
width: 70px;
height: 30px;
margin-right: 100px;
padding: 10px;
text-align: center;
background-color: greenyellow;
}
.box div {
line-height: 30px;
position: relative;
float: left;
width: 60px;
height: 30px;
margin: 10px;
cursor: pointer;
text-align: center;
background-color: #03a9f4;
}
.focus {
color: #f01400;
}
.box .underline {
position: absolute;
bottom: -2px;
left: 3px;
width: 50px;
height: 0;
margin: 0;
padding: 0;
animation: ease-in-out 0.2s slide;
border: 2px solid #f01400;
}
@keyframes slide {
0% {
width: 0;
}
100% {
width: 50px;
}
}
.box .buy {
width: 100px;
color: white;
border-radius: 10px;
background-color: black;
}
</style>
<body>
<div class="box">
<h2>慕课手机</h2>
<div class="text focus" data-index="1">首页
<div class="underline"></div>
</div>
<div class="text" data-index="2">外观</div>
<div class="text" data-index="3">配置</div>
<div class="text" data-index="4">型号</div>
<div class="text" data-index="5">说明</div>
<div class="buy">立即购买</div>
</div>
</body>
<script>
var box = document.querySelector(".box");
var box_textdiv = document.querySelectorAll(".text");
var index = null;
box.onmouseover = function (event) {
if (event.target.classList.contains("text")) {
var focus_div_index = document.querySelector(".focus").getAttribute("data-index");
box_textdiv[focus_div_index - 1].classList.remove("focus");
var underline = document.querySelector(".underline");
event.target.classList.add("focus");
event.target.appendChild(underline);
}
};
</script>
</html>1回答
好帮手慕小李
2023-02-01
同学你好,以上代码效果可以满足需求。另解释如下:
1、观察当鼠标移入的时候dom发生的变化。

当鼠标移入到“说明”后在当前的dom元素上添加上foucs类名,然后在观察其dom元素内部的变化如下:

可见仅在foucs类名元素中“插入了“<div class="underline"></div>那么回过来看js代码逻辑。

再结合看css

总结,underline的出现是以focus为准的,underline的位置是以box类名下的div为准的。
但这么写会有个问题如下:

祝学习愉快!
相似问题