Javascript實現scroll時固定html元素

來源:互聯網
上載者:User

代碼如下:

View Code

 1 (function($){ 2     var $window = $(window); 3  4     function createFixedCss(name, top) { 5         var doc = document, 6             heads = doc.getElementsByTagName("head"), 7             style = doc.createElement("style"), 8             cssText = "." + name + "{ position: fixed!important; top: " + top + "px!important; }"; 9 10         style.setAttribute("type", "text/css");11         if (style.styleSheet) {12             style.styleSheet.cssText = cssText;13         } else {14             style.appendChild(doc.createTextNode(cssText));15         }16 17         (heads.length ? heads[0] : doc.documentElement).appendChild(style);18     }19 20     $.fn.fixedTo = function ($container, distance) {21         var $this = this,22             cssName = "fixed" + Math.floor(Math.random()*1000000),23             distance = distance || 0,24             scroll = 0,25             offsetTop = distance;26 27         if ($container) { // container is a div element28             if (!($container instanceof $)) {29                 $container = $($container);30             }31             scroll = ($this.offset().top - $container.offset().top) - distance;32             offsetTop = $container.offset().top + distance;33         } else { // container is window34             $container = $window,35             scroll = $this.offset().top - distance;36         }37 38         createFixedCss(cssName, offsetTop);39 40         $container.scroll(function(e) {41             var scrollTop = $container.scrollTop();42             $this.toggleClass(cssName, scrollTop > scroll);43             return true;44         });45     };46 47 })(jQuery);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.