<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
body{
background-color: rgba(0,0,0,0.7);
}
ul{
position: relative;
}
li{
list-style: none;
float: left;
width: 83px;
height: 42px;
text-align: center;
cursor: pointer;
font: 400 16px/42px microsoft yahei;
}
.box{
width: 664px;
height: 42px;
margin: 200px auto;
background: #fff ;
position: relative;
border-radius: 7px;
}
span{
position: absolute;
width: 83px;
height: 42px;
left: 0;
top: 0;
border-radius: 7px;
background-color:pink;
}
</style>
<script>
window.onload = function () {
// 获取相关元素
var btn = document.getElementsByTagName("span")[0];
var ul = document.getElementsByTagName("ul")[0];
var liarr = ul.children;
var liwidth = liarr[0].offsetWidth;
//获取相关元素,绑定事件,书写事件驱动程序
var raw = 0;
for (var i = 0; i<liarr.length ;i++){
// 给元素绑定index属性;
liarr[i].index = i;
liarr[i].onmouseover = function () {
animate(btn,this.index*liwidth);
}
liarr[i].onmouseout = function () {
animate(btn,raw*liwidth);
}
liarr[i].onclick = function () {
raw = this.index;
}
}
//缓动动画封装
function animate(ele,target) {
clearInterval(ele.timer);
ele.timer = setInterval(function () {
var step = (target-ele.offsetLeft)/10;
step = step>0?Math.ceil(step):Math.floor(step);
ele.style.left = ele.offsetLeft + step + "px";
console.log(1);
if(Math.abs(target-ele.offsetLeft)<Math.abs(step)){
ele.style.left = target + "px";
clearInterval(ele.timer);
}
},18);
}
}
</script>
</head>
<body>
<div class="box">
<span></span>
<ul>
<li>首页新闻</li>
<li>首页新闻</li>
<li>首页新闻</li>
<li>首页新闻</li>
<li>首页新闻</li>
<li>首页新闻</li>
<li>首页新闻</li>
<li>首页新闻</li>
</ul>
</div>
</body>
</html>