实现思路如下:
div 初始居普通文档流中
给 window 添加 scroll 事件 (可事件节流), 获取 div 的 offset 的 top 值, 滚动时 scrollTop 值和 top 比较, 当到达 top 时给 div 添加一个 fixed 的 class 使其固定
向上滚动时当到达 div 初始 top 时则删除 fixed 的 class, 此时 div 又回到普通文档流中
fixed 样式非 IE6 浏览器使用 position:fixed,IE6 使用 position:absolute 和 IE expression
ps: 效果预览时请点击右上角全屏!
html 代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title > 吸顶 </title>
- <style media="screen">
- * {
- padding: 0;
- margin: 0;
- }
- #box {
- width: 100%;
- height: 50px;
- background-color: skyblue;
- }
- </style>
- <script type="text/javascript">
- window.onload = function () {
- var oBox = document.getElementById('box');
- var oBox2 = document.getElementById('box2');
- var top = oBox.offsetTop;
- window.onscroll = function () {
- var wScroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
- if (wScroll>= top) {
- oBox.style.position = 'fixed';
- oBox.style.top = '0';
- oBox.style.left = '0';
- oBox2.style.marginTop = '50px';
- } else {
- oBox.style.position = '';
- oBox2.style.marginTop = '0';
- }
- }
- }
- </script>
- </head>
- <body>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
以上 < br>
- <div id="box"> 嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤嘤 </div>
- <div id="box2">
- zhezhehhhh<br>
- zhezhehhhh<br>
- zhezhehhhh<br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
啦啦啦 < br>
- </div>
- </body>
- </html>
来源: http://www.qdfuns.com/article/29306/113222195b6f8e17a3c56cd3ebbfc6ef.html