首页 > 代码库 > 利用弹性运动的原理做弹性菜单

利用弹性运动的原理做弹性菜单

主要是速度以及临界条件的处理
弹性运动的函数
function startMove(obj,target) {
    clearInterval(obj.timer);
    var speed=0;
    obj.timer = setInterval(function() {
        speed += (target - obj.offsetLeft) / 6;
        //类似于摩擦系数
        speed *= 0.75;
        if(Math.abs(speed) < 1 && Math.abs(target - obj.offsetLeft) < 1) {
            clearInterval(obj.timer);
            obj.style.left = target;
            speed = 0;
        } else {
            obj.style.left = obj.offsetLeft + speed + ‘px‘;
        }
//        console.log(obj.offsetLeft + ‘/‘ + speed);
    }, 30);
}

 


<!
DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="../css/public.css"/> <style> #list{width: 450px;height: 40px;margin: 100px auto;position: relative;} #list li.box{width: 100px;height: 40px;line-height: 40px;text-align: center;border: 1px solid #999;float: left;margin-right: 10px;background: red;} #mark{width: 101px;height: 42px;background: green;position: absolute;top: 0;left: 0;} </style> <script type="text/javascript" src="../js/rainbow.js"></script> <script type="text/javascript"> window.onload=function(){ var oUl=document.getElementById("list"); var oMark=document.getElementById("mark"); var aBox=getElementsByClassName(document,li,box); var timer=null; for(var i=0;i<aBox.length;i++){ aBox[i].onmouseover=function(){ clearTimeout(timer); startMove(oMark,this.offsetLeft); }; aBox[i].onmouseout=function(){ timer=setTimeout(function(){ startMove(oMark,0); },100); } } oMark.onmouseover=function(){ clearTimeout(timer); }; oMark.onmouseout=function(){ startMove(oMark,0); } } </script> </head> <body> <ul id="list"> <li id="mark"></li> <li class="box">首页</li> <li class="box">论坛</li> <li class="box">体育</li> <li class="box">新闻</li> </ul> </body> </html>

 

利用弹性运动的原理做弹性菜单