Javascript实现scroll时固定html元素

代码如下:

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 element
28             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 window
34             $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);
posted @ 2012-12-03 14:53  ahui  阅读(1843)  评论(0编辑  收藏  举报