美文网首页
js 返回顶部

js 返回顶部

作者: 菜鸟搬砖 | 来源:发表于2018-12-12 13:56 被阅读8次

    最直接方式window.scrollTo(0,0)

    --------------------------分割线--------------------------------------------------------------

    function returnTop(){

        var scrollObj={

            scrollTop:0,

            winHeight:window.innerHeight,

            dom:null,

            bodyST:0,

            eleST:0,

            intervalTimer:null,

            init:function(dom){

                this.dom=dom

                let scrollHeight=document.body.scrollTop||document.documentElement.scrollTop;

                this.bodyST=document.body.scrollTop;

                this.eleST=document.documentElement.scrollTop;

                if(scrollHeight>this.winHeight){

                    dom.style.display='block'

                 }else{

                    dom.style.display='none'

                }

                    this.scroll()

                },

                scroll:function(){

                    var timer='10';

                    if(this.dom){

                        var _this=this;

                        this.dom.onclick=function(){

                        _this.intervalTimer=setInterval(function(){

                        let scrollHeight=document.body.scrollTop||document.documentElement.scrollTop;

                        let speed=scrollHeight/2

                        if(_this.bodyST!=0){

                            document.body.scrollTop -=speed

                        }else{

                            document.documentElement.scrollTop -=speed

                        }

                        if(scrollHeight==0){

                            clearInterval(_this.intervalTimer)

                        }

                    },timer )

                    }

                }

            }

        }

        return scrollObj;

    }

    window.addEventListener('scroll',function(){

        returnTop().init(document.getElementById('returntop'))

    })

    相关文章

      网友评论

          本文标题:js 返回顶部

          本文链接:https://www.haomeiwen.com/subject/bsguhqtx.html