惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
博客园_首页
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
MongoDB | Blog
MongoDB | Blog
美团技术团队
H
Help Net Security
G
Google Developers Blog
B
Blog RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
M
MIT News - Artificial intelligence
腾讯CDC
IT之家
IT之家
Vercel News
Vercel News
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
I
InfoQ
博客园 - 司徒正美
A
About on SuperTechFans

博客园 - ahui

解决在IIS中调用Microsoft Office Excel组件后进程无法正常退出的问题 [小技巧]提交数据并下载文件的实现方式 轻量级DbHelper同时支持多个不同的数据库 Emit实现简单的C# AOP框架 Reflector的替代方案 .NET2.0项目Ajax请求处理 EntityFramework4.1和ADO.NET插入操作性能比较 一道算法题(负数左边,正数右边)的最优答案 MVC+ExtJs之验证信息无缝结合 16进制字符串和Byte之间的互转 设置预览图片自适应(保持原比例) Entity Framework4.1实现动态多条件查询、分页和排序 C#读写socket的常用方式 异步接收Socket数据 Mysql备份代码 android下修改hosts文件 Android和.NET通用的AES算法 .NET和Android解压缩处理 Android轻量级JSON操作类
Javascript实现scroll时固定html元素
ahui · 2012-12-03 · via 博客园 - ahui

代码如下:

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);