js 缓冲框架

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{
    width:200px;
    height:200px;
    position:absolute;
    left:600px;
    top:50px;
    background:#F00;
}
#div2{
    width:1px;
    height:300px;
    position:absolute;
    left:300px;
    background:#000;
}
</style>
<script>

var timer=null;
function onStart(){
    var oDiv=document.getElementById('div1');
    clearInterval(timer);
    timer=setInterval(function(){
        
        var speed=(300-oDiv.offsetLeft)/10;
        
        speed=speed>0?Math.ceil(speed):Math.floor(speed);
        oDiv.style.left=oDiv.offsetLeft+speed+'px';
        
        },30);
    }
</script>
</head>

<body>
<input id="btn1" value="开始运动" type="button" onClick="onStart()" >
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>

缓冲菜单

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{
    width:100px;
    height:200px;
    position:absolute;
    right:0px;
    top:0px;
    background:#F00;

}
    #in{
        width:100px;
        height:20px;
        position:fixed;
        left:0px;
        top:0px;
    }
        


</style>
<script>
window.onscroll=function(){
    var oDiv=document.getElementById('div1');
    var scrollTop=document.documentElement.scroollTop||
    document.body.scrollTop;
    onStart(parseInt((document.documentElement.clientHeight-oDiv.offsetHeight)/2+scrollTop));
    }
var timer=null;
function onStart(Tag){
    var oDiv=document.getElementById('div1');
    clearInterval(timer);
    timer=setInterval(function(){
        var speed=(Tag-oDiv.offsetTop)/6;
        speed=speed>0?Math.ceil(speed):Math.floor(speed);
        if(oDiv.offsetTop==Tag){
            clearInterval(timer);
            }else{
                document.getElementById('in').value=Tag;
                oDiv.style.top=oDiv.offsetTop+speed+'px';
                }
        
        },30)
    }
</script>
</head>

<body style="height:2000px">
<input id="in" type="text">

<div id="div1"></div>

</body>
</html>

缓冲运动(一定不要忘记取整)
逐渐变慢,最后停止
距离越远速度越大
速度由距离决定
速度=(目标值-当前值)/缩放系数
例子:缓冲菜单
Bug:速度取整(必须取整 )
跟随页面滚动的缓冲侧边栏
潜在问题:目标值不是整数时

速度和距离成正比
如果 speed=0.9px ==0
speed=36.3 ==36
Math.ceil()向上取整
Math.floor()向下取整
滚动菜单
onscroll 滚动
clientHeight 可视框

-----------
匀速时 speed初始0

--------------

Math.abs()绝对值

 

posted @ 2017-05-10 23:00  943987243  阅读(126)  评论(0编辑  收藏  举报