First, the HTML
The HTML needs to give Div an ID
<body><div id="head"></div></body>
Second, 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>
Third, JS1, process-oriented
<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. Object-oriented 1) encapsulation method
/* * 封装吸顶函数,需结合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) Calling method
<script src="ceiling.js"></script><script> window.onload = function () { /*获取对象*/ var wrap = document.getElementById("head2"); ceiling(wrap) /*调用吸顶函数 */ };</script>
HTML Ceiling Effect