<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="reset.css"> <style> ul{ border-bottom: 2px solid #000; position: relative; } li{ display: list-item; float: left; width: 100px; height: 30px; background: #ccc; margin-left: 20px; } .bg{ height: 0px; border-bottom: 2px solid red; position: absolute; top: 30px; left: 0px; } </style> </head> <body> <ul class="clear"> <li class="bg"></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </body> </html>
CSS
reset.css
html{font-family:"微软雅黑",Arial,sans-serif}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,form,fieldset,input,button,textarea,p,th,td,b,i,strong{padding:0;margin:0;font-family:Microsoft YaHei,sans-serif,Arial}
strong,b{font-weight: normal;}
fieldset,img{border:0}
a{text-decoration:none;color:#000;outline:none}
li{list-style:none}
h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal}
input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit}
input,button,textarea,select{*font-size:100%}
.clear:after{
display:block;
content:"clear";
height:0;
clear:both;
visibility:hidden;
}
.clear{zoom:1;}
JS
<script> window.onload=function(){ var oul = document.getElementsByTagName("ul")[0]; var oli = document.getElementsByTagName("li"); var obg = oli[0]; var flog = true;
//获取下标值 添加触发事件 function getIndex(Eve,obj){ for(var i = 1;i<obj.length;i++){ obj[i].setAttribute("index",i); if(window.addEventListener){ obj[i].addEventListener(Eve,function(e){ moveTo(e.target.getAttribute("index")); },false); }else{ obj[i].attachEvent('on'+Eve,function(e){ moveTo(e.srcElement.index); }); } } } getIndex('mouseover',oli);
//根据下标值移动 function moveTo(index){ var end = (index-1)*120; var start = getDefaultStyle(obg,"left"); var step = (end-start)/10; console.log(time); if(flog){ flog = false; var time = setInterval(function(){ start+=step; console.log("start="+start); obg.style.left=start+"px"; if(start == end){ clearInterval(time); flog = true; } },10) } } //console.log(getDefaultStyle(obg,"left")); function getDefaultStyle(obj,attribute){ return parseFloat(obj.currentStyle?obj.currentStyle[attribute] : document.defaultView.getComputedStyle(obj,false)[attribute]); } //获取css元素的属性值; } </script>