时隔一年,window.scroll

function scrollToTop() {
        return function(btn, input) {
            var flag = false;
            var timer;

            function autoScroll(input) {
                var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
                if (scrollTop !== 0) {
                    timer = setInterval(function() {
                        var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
                        if (scrollTop === 0) {
                            clearInterval(timer);
                        } else {

                            scrollTop -= (document.body.scrollTop) / 8;
                            document.documentElement.scrollTop = document.body.scrollTop = (scrollTop < 5 ? scrollTop = 0 : scrollTop);
                            input.value = scrollTop;
                            flag = true;
                        }
                    }, 50);
                }
            }
            window.onscroll = function() {
                if (!flag) {
                    clearInterval(timer);
                }
                flag = false;
            };

            btn.onclick = function() {
                autoScroll(input);
            };
        };
    }

看了看14年底写的关于页面滚动的代码,居然还是有让我值得思考才能想明白的问题.顿时觉得进步有限.今天我把曾经的代码做了一个封装.避免了全局变量的出现.代码如上.

使用方法:

 window.onload = function() {
        var btn = document.getElementsByTagName('button')[0];
        var oInput = document.getElementsByTagName('input')[0];
        var s = scrollToTop();
        s(btn, oInput);
 };

 

posted @ 2015-12-22 10:21  杯酒红尘  阅读(145)  评论(0编辑  收藏  举报