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

如何设置CSS实现网页向下滚动时移动指定区块的效果

实现方案

方案1:纯CSS实现(推荐,无需JS,兼容绝大多数现代浏览器)

核心使用CSS position: sticky属性实现滚动吸附效果,元素滚动到设定的阈值位置时会自动固定在视口顶部,回滚到原始位置后自动恢复原有布局,不会导致内容跳动。
在现有CSS的.title规则中新增如下属性即可:

.content .main .title {
  font-size: 60px;
  height: 100px;
  background-color: #71ff05;
  margin-bottom: 20px;
  padding: 10px;
  /* 新增以下样式 */
  position: sticky;
  top: 0;
  z-index: 999; /* 确保吸顶时层级最高,不被其他内容遮挡 */
  box-sizing: border-box; /* 避免border、padding导致宽度溢出 */
}

如果需要吸顶时宽度撑满整个视口,仅需额外调整吸顶状态下的宽度参数即可。

方案2:JS兼容方案(适配不支持sticky的老旧浏览器)

如果需要兼容极旧版本浏览器,可以通过监听滚动事件实现:
首先新增固定定位的专用CSS类:

.title.fixed {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  margin: 0;
}

再添加对应JS逻辑:

const title = document.querySelector('.title')
const titleOffsetTop = title.offsetTop
const main = document.querySelector('.main')
window.addEventListener('scroll', () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  if (scrollTop >= titleOffsetTop) {
    title.classList.add('fixed')
    // 给主内容添加占位padding,避免标题脱离文档流导致内容突然上跳
    main.style.paddingTop = '142px'
  } else {
    title.classList.remove('fixed')
    main.style.paddingTop = '20px'
  }
})

内容的提问来源于stack exchange,提问作者AWEI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:27:04