JavaScript緩衝運動のディザリング防止

5162 ワード


<html>
<head>
    <meta charset="utf-8">
    <title>GuoYu-ajaxtitle>
    <style type="text/css">
        #div1 {
            width: 100px;
            height: 200px;
            background: red;
            position: absolute;
        }
    style>
head>
<body style="height: 500000px;">
    <div id="div1">div>

    <script type="text/javascript">
        var oDiv = document.getElementById('div1');
        window.onscroll = function() {
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            //oDiv.style.top = document.documentElement.clientHeight - oDiv.offsetHeight + scrollTop + 'px';
            //      ,   ,         ,    
            startMove(parseInt((document.documentElement.clientHeight - oDiv.offsetHeight) / 2 + scrollTop));
        }

        var timer = null;
        function startMove(iTarget) {
            console.log('oDiv.offsetTop = ' + oDiv.offsetTop);
            clearInterval(timer);
            timer = setInterval(function() {
                var speed = (iTarget - oDiv.offsetTop) / 6;
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

                if (oDiv.offsetTop == iTarget) {
                    clearInterval(timer);
                } else {
                    document.title = iTarget + ',' + oDiv.offsetTop;
                    //  ,  div     ,iTarget 774.5,offsetTop     774 775,    
                    //         speed    ,
                    /*
                        var speed = (774.5 - 774)/6;speed => 1, 774 -> 775;    774.5,
                          speed => -1,775 -> 774,       ,     774.5 。
                            :      ,      ,        ,     ,     。
                                           。
                           = (    -    )/     
                    */
                    oDiv.style.top = oDiv.offsetTop + speed + 'px';
                }
            }, 30);
        }
    script>
body>
html>