很喜欢这个效果,可以经常练习,这个效果的难点在于一个缓动运动,以及蓝条跟随鼠标移动
<div class="nav-box" id="nav-box">
<a href="#" class="nav-item">Griffin</a>
<a href="#" class="nav-item">Paul</a>
<a href="#" class="nav-item">Tomas</a>
<a href="#" class="nav-item">Holiday</a>
<a href="#" class="nav-item">Curry</a>
<span class="line" id="line"></span>
</div>
用一个盒子,里面是五个a标签,因此要给a标签display:block
html,body{
margin: 0;
padding: 0;
}
.nav-box{
width: 800px;
height: 56px;
background-color: #BAB5B9;
position: relative;
margin: 100px auto;
}
.nav-item{
width:150px;
height:56px;
line-height: 56px;
background-color: indianred;
text-align: center;
display: block;
float: left;
border-right: 1px solid #BAB5B9;
color: #fff;
font-size: 20px;
font-family: "微软雅黑";
text-decoration: none;
}
.line{
width: 150px;
position: absolute;
height: 5px;
background-color: dodgerblue;
left: 0;
bottom: -5px;
}
span做的蓝条要相对盒子进行绝对定位,来调整位置
js部分
1.要注意用getElementsByClassName获取到的是一个html集合,在循环中操作要带上索引
2.先验证有不有定时器的存在
3.运动部分封装在函数里
<script>
var getitem = document.getElementsByClassName('nav-item');
//var getitem = document.getElementById("nav-box").getElementsByTagName("a");
var getline = document.getElementById("line");
//alert(getline.nodeName); 打印出来的标签名是大写
//alert(getitem[0].nodeName);
var timer = null;
getline.style.left =0; //不进行赋空没效果?
for (var i = 0;i < getitem.length;i++) {
getitem[i].onmouseenter = function(){
if(timer){
clearTimeout(timer);
} //清除已存在的定时器
var start = parseInt(getline.style.left);
var end = this.offsetLeft; //元素的边框的外边缘距离与已定位的父容器(offsetparent)的左边距离
move(start,end);
}
}
function move(startpos,endpos){
var step = (endpos - startpos)/10;
if(step > 0){
step = Math.ceil(step);
}else{
step = Math.floor(step);
}
startpos = startpos + step;
getline.style.left = startpos + "px";
if(startpos == endpos){
clearTimeout(timer);
}else{
timer = setTimeout(function(){
move(startpos,endpos);
},16);
}
}
</script>