如何用JavaScript实现元素在指定滚动高度区间内固定定位?
解决方案
你的代码需要调整判断逻辑,同时修正几个小问题,就能实现指定滚动区间内固定元素的效果:
- 统一滚动高度获取方式:兼容不同浏览器,用
document.documentElement.scrollTop || document.body.scrollTop获取当前滚动距离 - 添加区间上限判断:当滚动高度在
4680-5800之间时添加固定类,否则移除 - 修正元素ID不一致问题:代码中同时出现了
about-txt和about-text,要统一为同一个ID - 安全移除类:用
classList.remove()替代className = "",避免清空元素其他类
修改后的JavaScript代码
window.onscroll = function () { myFunction(); }; function myFunction() { // 获取当前滚动高度,兼容不同浏览器 const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; const targetElement = document.getElementById("about-txt"); // 统一ID if (scrollTop >= 4680 && scrollTop <= 5800) { targetElement.classList.add("about-option"); } else { targetElement.classList.remove("about-option"); } }
补充CSS默认样式
为了确保元素在非固定状态下恢复position:relative,给目标元素添加默认样式:
#about-txt { position: relative; } .about-option { position: fixed; top: 20%; width: 40%; right: 7%; }
这样就能实现:当页面滚动到4680px及以上、5800px及以下时,元素变为固定定位;滚动到区间外时,自动恢复相对定位。
内容的提问来源于stack exchange,提问作者willscode
相关产品推荐
相关产品推荐

