You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现元素在指定滚动高度区间内固定定位?

解决方案

你的代码需要调整判断逻辑,同时修正几个小问题,就能实现指定滚动区间内固定元素的效果:

  1. 统一滚动高度获取方式:兼容不同浏览器,用document.documentElement.scrollTop || document.body.scrollTop获取当前滚动距离
  2. 添加区间上限判断:当滚动高度在4680-5800之间时添加固定类,否则移除
  3. 修正元素ID不一致问题:代码中同时出现了about-txt和about-text,要统一为同一个ID
  4. 安全移除类:用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:45:36