运动之分享到

匀速运动和缓冲运动的结合:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上下滑动的侧边栏</title>
    <style>
        body{height:2000px;}
        #div1{width:100px;height:200px;background-color:yellow;position:absolute;left:-100px;top:0;}
        span{width:20px;position:absolute;right:-20px;background-color:black;color:white;text-align:center;}
    </style>
</head>
<body>
<div id="div1">
    <span>分享到</span>
</div>
</body>
</html>
<script type="text/javascript">
    window.onload = function () {
        var oDiv = document.getElementById("div1");
        oDiv.onmousemove = function () {
            startMove(0);
        }
        oDiv.onmouseout = function () {
            startMove(-100);
        }
    }
    var timer = null;

    //    左右匀速运动
    function startMove(iTarget) {//通过目标点来计算速度
        var oDiv = document.getElementById("div1");
        clearInterval(timer);
        timer = setInterval(function () {
            var iSpeed = 0;
            if(oDiv.offsetLeft<iTarget){
                iSpeed = 7;
            }else{
                iSpeed = -7;
            }
            if(Math.abs(oDiv.offsetLeft-iTarget)<7){
                clearInterval(timer);
                oDiv.style.left = iTarget+'px';
            }else{
                oDiv.style.left = oDiv.offsetLeft+iSpeed+"px";
            }
        },30)
    }


    window.onscroll=function ()
    {
        var oDiv=document.getElementById('div1');
        var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;

        //oDiv.style.top=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2+'px';
        var t=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2;

        startMove2(parseInt(t));
    }
    //上下缓冲运动
    function startMove2(iTarget)
    {
        var oDiv=document.getElementById('div1');
        clearInterval(timer);
        timer=setInterval(function (){
            var iSpeed=(iTarget-oDiv.offsetTop)/8;
            iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
            if(oDiv.offsetTop==iTarget)
            {
                clearInterval(timer);
            }
            else
            {
                oDiv.style.top=oDiv.offsetTop+iSpeed+'px';
            }
        }, 30);
    }
</script>

 

posted @ 2016-11-02 14:31  最爱小虾  阅读(145)  评论(0编辑  收藏  举报