效果如下:
代码如下:
head部分
<style>
body, ul {
margin: 0px;
padding: 0px;
}
.header {
width: 100%;
height: 75px;
background-color: #333;
}
.nav_wrap {
position: relative;
width: 900px;
height: 75px;
margin: 0 auto;
}
.nav_wrap ul {
list-style: none;
}
.nav_wrap ul li {
float: left;
width: 150px;
height: 75px;
font: 500 18px/75px "simsun";
text-align: center;
color: #fff;
cursor: pointer;
}
span {
position: absolute;
left: 0px;
bottom: 1px;
display: inline-block;
height: 4px;
width: 150px;
background-color: #fff;
}
.nav_wrap ul li.current {
background-color: #000;
color: #fff;
}
</style>
<script>
window.onload = function () {
//需求:当鼠标滑过任意的栏目时,下面的小长方形都会滑动跟随
//1.获取相关元素
var nav_wrap = document.getElementById("nav_wrap");
var liArr = nav_wrap.children[0].children;
var width = liArr[0].offsetWidth;
var span = nav_wrap.children[1];
//遍历li元素
for(var i=0; i<liArr.length; i++){
liArr[i].index = i;
//当滑过li时,span开始运动
liArr[i].onmouseover = function () {
for(var j=0; j<liArr.length; j++){
liArr[j].className = "";
}
this.className= "current";
animate(span, this.index*width);
}
//当鼠标离开全部的元素时,回到刚开始的状态
liArr[i].onmouseout = function(){
for(var k=0; k<liArr.length; k++){
liArr[k].className = "";
}
animate(span,0);
liArr[0].className = "current";
}
}
//2.书写事件驱动程序
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";
var val = target-ele.offsetLeft;
if(Math.abs(val)<Math.abs(step)){
ele.style.left = target +"px";
clearInterval(ele.timer);
}
},20)
}
}
</script>
body部分
<div class="header">
<div class="nav_wrap" id="nav_wrap">
<ul>
<li class="current">活动首页</li>
<li>榜单设置</li>
<li>榜单投票</li>
<li>抽奖活动</li>
<li>活动报名</li>
<li>活动评审</li>
</ul>
<span class="side"></span>
</div>
</div>