JS實現側懸浮浮動執行個體代碼

來源:互聯網
上載者:User

效果:

思路:

首先,載入onscroll控制捲軸。然後寫緩衝運動的方法,緩衝運動的方法是先計算出DIV緩衝的速度,並且將其取整,再進行運動判斷什麼時候到達終點。最後將其參數返回。再在onscroll裡面調用此方法,並且將終點計算出來賦予此方法的參數。

代碼:
複製代碼 代碼如下:
<head runat="server">
    <title></title>
    <style type="text/css">
        #div1
        {
            width: 200px;
            height: 200px;
            background: #0000FF;
            position: absolute;
            right: 0;
            bottom: 0;
        }
    </style>
    <script type="text/javascript">
        window.onscroll = function () {
            var oDiv = document.getElementById('div1');
            var DivScroll = document.documentElement.scrollTop || document.body.scrollTop;      //擷取移動高度
            //                        oDiv.style.top = (document.documentElement.clientHeight - oDiv.offsetHeight)/2 + DivScroll + 'px';
            move(parseInt((document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + DivScroll));    //調用傳參,其中裡面的參數是DIV要走的終點。也就是(可視高度-DIV高度)/2+移動高度
        };

        var timer = null;
        function move(end) {
            clearInterval(timer);       //首先,先關閉之前如果有開啟的setInterval;
            timer = setInterval(function () {      
                var oDiv = document.getElementById('div1');
                var speed = (end - oDiv.offsetTop) / 5;     //計算DIV要走的速度,DIV要走的速度就等於(終點-offsetTop高度)/縮放係數
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);       //為了避免小數,將其取整
                if (oDiv.offsetTop == end) {        //當DIV到達終點,則關閉setInterval;
                    clearInterval(timer);
                }
                else {
                    oDiv.style.top = oDiv.offsetTop + speed + 'px';     //移動div
                }
            }, 30);
        }
    </script>
</head>
<body style="height: 1000px;">
    <div id="div1">
    </div>
</body>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.