【js基本功能模块】“回到顶部”代码优化

以前项目里面“回到顶部”思路是:动态插入div,设置相对定位,ie6绝对定位,窗口"resize,scroll"的时候动态改变位置,即使是相对定位的时候,也要动态计算位置。

新的思路: 动态插入一个div(如下图),居中,相对定位,然后计算下位置,里面的元素,支持fixed,用fixed,IE6,单独计算,这么做的好处是,在窗口resize,scroll的时候,支持fixed的浏览器不用再重新计算元素的位置了,IE6难免的,还是要计算 

顺便我把项目的里面的代码片段贴一下

    var TOPPANEL = "#MST-common-panel",
        SIDEPANEL = "#MST-common-sidepanel",
        SUGGESTCLASS = ".MST-common-suggest",
        GOTOTOPCLASS = ".MST-common-goTop",
        TPL = {
            wrap : '<div style="950px;position:relative;margin:0 auto;" id="MST-common-panel"></div>',
            innerWrap : '<div id="MST-common-sidepanel" style="position: fixed; bottom: 10px; display: none;30px;z-index:9999" class="undis"></div>',
            inner : '<a class="get-back MST-common-goTop" href="javascript:void(0);" title="返回顶部">返回顶部</a>'
        }
    
    var goToTop = function() {
        if (!$(TOPPANEL).size()) {
            $(document.body).prepend(TPL.wrap)
        }
        $(TOPPANEL).append(TPL.innerWrap);
        var $wrap = $(SIDEPANEL);
        this.init = function() {
            var self = this,
                $window = $(window);
            self.setTop();
            self.initCss();
            $window.bind({
                "scroll" :     function() {
                    (document.body.scrollTop || document.documentElement.scrollTop) === 0 ? $wrap.hide() : $wrap.show();
                    $.isIE6 && setTimeout(function(){
                        self.initCss();                    
                    }, .5 * 1000);
                },
                "resize" : function() {
                    $.isIE6 && setTimeout(function(){
                        self.initCss();                    
                    }, .5 * 1000);
                }
            });            
        };
        this.initCss = function() {
            var cssObj, windowWidth = 950,$window = $(window);
            $.isIE6 ? cssObj = {
                right: "-40px",
                position : "absolute",
                top : $window.scrollTop() + $window.height() - 10 - $wrap.height()
            } : cssObj = {
                right: (document.documentElement.clientWidth - windowWidth) / 2 - 30 - 10 + "px"
            };
            $wrap.css(cssObj);
        };
        this.addCss = function(cssObj) {
            $wrap.css(cssObj);
        };
        this.addItem = function(str) {
            $wrap.append(str);
        };
        this.setTop = function() {
            this.addItem(TPL.inner);
            $wrap.find(GOTOTOPCLASS).click(function(){
                window.scrollTo(0, 0);
                return false;
            });
        }
    };   
原文地址:https://www.cnblogs.com/sniper007/p/2766757.html