<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> body,ul{margin:0;padding:0;} ul{width:400px;height:30px;position:relative;margin:20px auto;} li{width:98px;height:28px;border:1px solid black;float:left;line-height:28px;text-align:center;list-style:none;} .bg{width:100px;height:5px;background:red;position:absolute;left:0;bottom:0;overflow:hidden;border:none;} </style> <script> window.onload =function(){ var oUl = document.getElementsByTagName('ul')[0]; var arrLi = oUl.getElementsByTagName('li'); var oBg = arrLi[arrLi.length-1]; for(var i=0;i<arrLi.length-1;i++){ arrLi[i].onmouseover = function(){ elasticStartMove(oBg,this.offsetLeft); }; } }; var left = 0; /*必须放在外面,解决小数误差问题*/ function elasticStartMove(obj,target){ var speed = 0; clearInterval(obj.timer); obj.timer = setInterval(function(){ speed += (target-obj.offsetLeft)/5; speed *= 0.75; left += speed; if(Math.abs(speed) < 1 && Math.abs(left-target) < 1){ /*停止的条件*/ clearInterval(obj.timer); obj.style.left = target+'px'; } obj.style.left=left+'px'; document.title="speed:"+speed+" - :"+Math.abs(left-target); },30); } /* 弹性公式: 速度 +=(目标值-oDiv.offsetLeft)/5 速度*=0.7; 不适用范围:对于有一些height不能取负数的不能使用 */ </script> </head> <body> <ul> <li>首页</li> <li>产品</li> <li>关于我们</li> <li>联系方式</li> <li class='bg'></li> </ul> </body> </html>