javascript返回顶部代码


javascript返回顶部代码

<div id="returnTop">
        <a></a>
    </div>
var oDiv = document.getElementById('returnTop');
        oDiv.onclick = function() {
            startMove(0);
        };
        var timer = null;

        function startMove(iTarget) {
            clearInterval(timer);
            timer = setInterval(function() {
                var bBtn = true;
                var scrollY = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
                var iSpeed = (iTarget - scrollY) / 8;
                iSpeed = Math.floor(iSpeed);
                if (scrollY != iTarget) {
                    bBtn = false;
                };
                document.documentElement.scrollTop = document.body.scrollTop = scrollY + iSpeed;
                window.onscroll = function() {
                    if (bBtn) {
                        clearInterval(timer);
                    } else {
                        bBtn = true;
                    }
                };
            }, 30);
        };

        if (!!window.attachEvent) {
            window.attachEvent("onscroll", function() {
                var scrollY = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
                if (scrollY) {
                    oDiv.style.display = 'block';
                } else {
                    oDiv.style.display = 'none';
                }
            }, false)
        }

        if (!!window.addEventListener) {
            window.addEventListener("scroll", function() {
                var scrollY = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
                if (scrollY) {
                    oDiv.style.display = 'block';
                } else {
                    oDiv.style.display = 'none';
                }
            }, false)
        }

 

Archives