首先写HTML布局css
<body> <div id="wrap"></div> </body>
给点简单的样式git
<style> *{ margin: 0; padding: 0; } body{ height: 2000px; background-image: linear-gradient(-180deg, #15f09d 0%, #25A0FF 50%, #fca72b 100%); } #wrap{ background-color: rgba(0,0,0,0.2); width: 100%; height: 100px; margin-top: 100px; } #wrap[data-fixed="fixed"]{ position: fixed; top:0; left: 0; margin: 0; } </style>
直接编写5行代码搞定github
<script> var obj = document.getElementById("wrap"); var ot = obj.offsetTop; document.onscroll = function () { var st = document.body.scrollTop || document.documentElement.scrollTop; obj.setAttribute("data-fixed",st >= ot?"fixed":"")} </script>
JS改进,封装成吸顶函数 ceiling.js 方便之后直接Ctrl+C,Ctrl+V数组
/* * 封装吸顶函数,需结合css实现。 * 也能够直接用js改变样式,能够自行修改。 */ function ceiling(obj) { var ot = obj.offsetTop; document.onscroll = function () { var st = document.body.scrollTop || document.documentElement.scrollTop; /* * 在这里我给obj添加一个自定义属性。className可能会影响原有的class * 三元运算使代码更简洁 */ obj.setAttribute("data-fixed",st >= ot?"fixed":""); } }
<script src="ceiling.js"></script> <script> window.onload = function () { /*获取导航对象*/ var wrap = document.getElementById("wrap"); ceiling(wrap) /*调用吸顶函数 */ }; </script>
这是最简单版本,欢迎你们在此基础上改进。函数
.tab-list[data-fixed="fixed"] { position: fixed; top: 0; left: 0; margin: 0; }
function arrCeiling(arr) { var ot = []; arr.forEach(function(item, i) { ot.push(item.offsetTop); }) document.onscroll = function() { var st = document.body.scrollTop || document.documentElement.scrollTop; arr.forEach(function(item, i) { console.log(st, ot) item.setAttribute("data-fixed", st >= ot[i] ? "fixed" : ""); }) } } window.onload = function() { /*获取导航数组*/ var arr = document.querySelectorAll('.tab-list') arrCeiling(arr) };
案例:
5行js代码搞定导航吸顶效果布局