JS实现右侧悬浮框随着页面的上下轮动而移动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #div{
            width: 200px;
            height: 100px;
            background: red;
            position: absolute;
            right: 0;
            bottom: 40%;
        }
    </style>
    <script>
        window.onscroll = function () {
            var oDiv = document.getElementById('div');
            var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
            //oDiv.style.top = (document.documentElement.clientHeight-oDiv.offsetHeight)/2+scrollTop+'px';
            startMove(parseInt((document.documentElement.clientHeight-oDiv.offsetHeight)/2+scrollTop));
        };
        var time = null;
        function startMove(iTarget){
            var oDiv = document.getElementById('div');
            clearInterval(time);
            time = setInterval(function(){
                var speed = (iTarget-oDiv.offsetTop)/6;
                speed = speed>0?Math.ceil(speed):Math.floor(speed);
                if(oDiv.offsetTop == iTarget){
                    clearInterval(time)
                }else{
                    oDiv.style.top = oDiv.offsetTop+speed+'px';
                }
            },30)
        }
    </script>
</head>
<body style="height: 2000px;">
    <div id="div"></div>
</body>
</html>

  

posted @ 2020-10-10 10:17  YH丶浩  阅读(403)  评论(0编辑  收藏  举报