js代码注释如下
function menuFixed(id) {
var obj = document.getElementById(id);//获取传入的id参数对应的dom对象,即nav_keleyi_com这个dom
//获取dom对象相对于offsetParent 节点顶部边界的偏移像素值,offsetTop参考https://www.runoob.com/jsref/prop-element-offsettop.html这篇文文章
//offsetParent参考https://blog.csdn.net/u012532033/article/details/72851692
eight = obj.offsetTop;
window.onscroll = function () {//注册页面滚动事件
changePos(id, eight)//调用changePos函数
}
}
function changePos(id, height) {
var obj = document.getElementById(id);//这里应该用传入的id参数值,当然直接写死也可以,写死了id参数就没意义了
//这里主要获取滚动高度用,做了兼容。当启用了xhtml,就是有最顶部的doctype html文档申明时
//文档是CSS1Compat模式,获取滚动高度用document.documentElement.scrollTop获取,document.body.scrollTop值为0
//去掉xhtml申明,为backcompat模式(document.documentElement.scrollTop值为0),用document.body.scrollTop获取
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop < height)//滚动高度小于nav_keleyi_com对象的offsetTop值时设置位置为relative保持原位置不变
obj.style.position = 'relative'
else//滚动高度超过dom对象的offsetTop,设置为fixed定义,top 0px,不论怎么往下继续滚动,自动固定到页面顶部,
//fixed定位参考https://blog.csdn.net/qq_43247538/article/details/125728170
obj.style.position = 'fixed'
}
window.onload = function () {//网页资源全部加载完毕后触发的事件
menuFixed('nav_keleyi_com')//调用menuFixed函数
}
还有一个新的属性粘性定位(sticky),这个不要js,直接css就能搞定,参考这篇文章:https://blog.csdn.net/weixin_51081257/article/details/121305642
不过和js控制有点出入,滚动到父容器底部后就不会继续滚动了,这个需要注意。看下面的示例
<body style="height:2300px">
<div id="nav_keleyi_com" style="position:sticky;top:0;background:#00f;width:100px;height:100px">
<span style="color:aliceblue">到底body容器底部后停止浮动</span>
</div>
<div style="height:200px"></div>
<div style="border:1px solid;width:500px;height:1000px">
<div id="nav_keleyi_com" style="position:sticky;top:0;background:#00f;width:100px;height:100px">
<span style="color:aliceblue">到底height 1000px容器底部后停止浮动</span>
</div>
</div>
</body>
🚀 通俗易懂的实现方式,帮助我们认识相应的方法
📚 收藏本系列,基础进阶两不误
🎉 本系列持续更新,欢迎查看线上地址