移动下标效果
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{ margin: 0; padding: 0; }
li{ list-style: none; }
ul{ width: 400px; height: 30px; position: relative; margin: 100px auto 0;}
li{ float: left; width: 98px; height: 28px; line-height: 28px; border: 1px solid #ccc; text-align: center; z-index: 2; position: relative; cursor: pointer;}
.bg{ width: 100px; height: 5px; overflow: hidden; background: steelblue; position: absolute; top: 24px; left: 0; z-index: 1; border: none;}
</style>
</head>
<body>
<ul id="ul1">
<li>LINK 1</li>
<li>LINK 2</li>
<li>LINK 3</li>
<li>LINK 4</li>
<li class="bg"></li> <!--哦,原来这个li是下面那个小东西啊-->
</ul>
<script type="text/javascript">
window.onload = function(){
var oUl = document.getElementById("ul1");
var aLi = oUl.getElementsByTagName("li");
var oBg = aLi[aLi.length -1]; //下标li
var i = 0;
for(i = 0; i<(aLi.length-1); i++){ /*给每个li加上事件*/
aLi[i].onmouseover = function(){
startMove(oBg, this.offsetLeft);
// alert(this.offsetLeft)
//传入两个参数,一个是这个下标,第二个是li的offsetLeft
};
}
};
var iSpeed = 0;
var left = 0;
function startMove(obj, iTarget){
// obj.style.left = iTarget + 'px';
clearInterval(obj.timer)
//// 用计时器来控制速度
obj.timer = setInterval(function(){
iSpeed+=(iTarget - obj.offsetLeft)/5;
//// 当前li的offsetLeft减去下标的offsetLeft
iSpeed*=0.7;
console.log(iSpeed);
left +=iSpeed;
// 这里的1 用来控制出去的一小段的大小
if(Math.abs(iSpeed)<0 && Math.abs(left - iTarget)<0){
clearInterval(obj.timer);
obj.style.left = iTarget + 'px';
}else{
obj.style.left = left + 'px';
}
}, 30);
}
</script>
</body>
</html>