html和css样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
background-color: black;
}
a {
display: block;
height: 100%;
width: 100%;
text-align: center;
text-decoration: none;
color: rgb(8, 8, 8);
}
.box {
position: relative;
background-color: rgb(253, 253, 253);
}
ul {
position: relative;
line-height: 40px;
width: 640px;
}
li {
display: inline-block;
height: 40px;
width: 100px;
list-style: none;
}
.span {
z-index: 0;
position: absolute;
left: 40px;
top: 0;
width: 100px;
height: 40px;
background-color: brown;
display: block;
}
</style>
</head>
<body>
<div class="box">
<span class="span"></span>
<ul>
<li class="li"><a href="#">新闻首页</a></li>
<li><a href="#">师资力量</a></li>
<li><a href="#">活动策划</a></li>
<li><a href="#">企业文化</a></li>
<li><a href="#">招聘信息</a></li>
<li><a href="#">新闻首页</a></li>
</ul>
</div>
</body>
<script>
var box = document.querySelector(".box");
var span = document.querySelector(".span");
var lis = document.querySelectorAll("li");
var cost = 40
for (var i = 0; i < lis.length; i++) {
lis[i].addEventListener("mousemove", function() {
animation(span, this.offsetLeft);
});
lis[i].addEventListener("mouseout", function() {
animation(span, cost);
});
lis[i].addEventListener("click", function() {
cost = this.offsetLeft;
});
}
</script>
</html>
animation函数的封装
function animation(obj, target) {
clearInterval(obj.time);
obj.time = setInterval(function() {
var step = (target - obj.offsetLeft) / 10;
if (obj.offsetLeft == target) {
clearInterval(obj.time);
}
step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style.left = obj.offsetLeft + step + "px";
}, 15)
}