JavaScript侧边悬浮框

<script>
    window.onscroll=function(){

        var oDiv=document.getElementById('div1');
        var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
        oDiv.style.top=(document.documentElement.clientHeight-oDiv.offsetHeight)/2+scrollTop+'px';
        startMove((document.documentElement.clientHeight-oDiv.offsetHeight)/2+scrollTop);
        
    };
    
        var timer=null;

    function startMove(iTarget){

        var oDiv=document.getElementById('div1');
        clearInterval(timer);


        timer=setInterval(function(){

            var speed=(iTarget-oDiv.offsetTop)/8;
            speed=speed>0?Math.ceil(speed):Math.floor(speed);
            if(oDiv.offsetTop==iTarget)
                clearInterval(timer);
                
            else
                odiv.style.top=oDiv.offsetTop+speed+'px';
            
        },30);
    }

    

    </script>

一个小小的js悬浮框,也是有很多很多的细节要注意。。。

基础的运动框架套路不能忘记。。。 

使用math函数解决可能存在的因为数学问题而导致鼠标停止时的闪烁。。。

代码本质其实是用缓冲运动解决掉悬浮框闪烁的问题,提高视觉体验。。。

如果不用debug,还是撸代码撸到要死。。。。

原文地址:https://www.cnblogs.com/jokerspace/p/5719045.html