一、HTML
HTML中需要给div一个id
<body><div id="head"></div></body>
二、CSS
<style> ?#head2 { ?????background-color: #989898
; ?????width: 100%; ?????height: 100px; ?????margin-top: 100px; ?} ?#head2 [data-fixed="fixed"]{ ?????position: fixed; ?????top:0; ?????left: 0; ?????margin: 0; ??}
</style>
三、JS
1、面向过程
<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>
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("head2"); ???????ceiling(wrap) /*调用吸顶函数 ?*/ ???};</script>
Html吸顶效果
原文地址:https://www.cnblogs.com/Michelle20180227/p/8487035.html