Html吸頂效果
一、HTML
HTML中需要給div一個id
?
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"> </head> <body> <div id="head"></div> </body> </html>
?
二、CSS
<style>#head {background-color: #989898;width: 100%;height: 100px;margin-top: 100px;}#head[data-fixed="fixed"]{position: fixed;top:0;left: 0;margin: 0;}</style>
html文字特效,?
三、JS
1、面向過程
<script>var obj = document.getElementById("head");var ot = obj.offsetTop;document.onscroll = function () {var st = document.body.scrollTop || document.documentElement.scrollTop;obj.setAttribute("data-fixed",st >= ot?"fixed":"")} </script>
?
2、面向對象
1)封裝方法
/* * 封裝吸頂函數,需結合css實現。* 也可以直接用js改變樣式,可以自行修改。*/function ceiling(obj) {var ot = obj.offsetTop;document.onscroll = function () {var st = document.body.scrollTop || document.documentElement.scrollTop;obj.setAttribute("data-fixed",st >= ot?"fixed":"");}}
?
2)調用方法
<script src="ceiling.js"></script> <script>window.onload = function () {/*獲取對象*/var wrap = document.getElementById("head");ceiling(wrap) /*調用吸頂函數 */}; </script>
?