首页 > 代码库 > 缓冲运动(上下跟随侧边栏)

缓冲运动(上下跟随侧边栏)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>滑动侧边栏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #div1 {
            width: 100px;
            height: 100px;
            position: absolute;
            right: 0;
            background: red;
        }
    </style>
    <script>
        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);
            startMove(parseInt(t));//有分数,为了防止出现小数,则取整
        }
        var timer = null;

        function startMove(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);//小于0向上取整,大于0向下取整
                if (oDiv.offsetTop == iTarget) {
                    clearInterval(timer);
                } else {
                    oDiv.style.top = oDiv.offsetTop + iSpeed + ‘px‘;
                }
                txt1.value = http://www.mamicode.com/oDiv.offsetTop;"height:100000px;">
    <div id="div1"></div>
    <input type="text" name="" value="" id="txt1" style="position:fixed">
</body>

</html>

 

查看范例

缓冲运动(上下跟随侧边栏)