很喜歡這個效果,可以經(jīng)常練習(xí),這個效果的難點在于一個緩動運動,以及藍條跟隨鼠標(biāo)移動
<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標(biāo)簽,因此要給a標(biāo)簽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做的藍條要相對盒子進行絕對定位,來調(diào)整位置
js部分
1.要注意用getElementsByClassName獲取到的是一個html集合,在循環(huán)中操作要帶上索引
2.先驗證有不有定時器的存在
3.運動部分封裝在函數(shù)里
<script>
var getitem = document.getElementsByClassName('nav-item');
//var getitem = document.getElementById("nav-box").getElementsByTagName("a");
var getline = document.getElementById("line");
//alert(getline.nodeName); 打印出來的標(biāo)簽名是大寫
//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>
捕風(fēng)格化獲.PNG
navbar.gif