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

如何用HTML/CSS/JS实现仅网站指定区域触发parallax视差效果

调整方案

1. 修正CSS样式

首先调整两个样式规则,解决容器溢出和下方内容布局错位的问题:

/* 原有#welcome规则基础上新增属性 */
#welcome {
  color: #000;
  height: 100vh;
  position: relative;
  overflow: hidden; /* 限制视差元素仅在头部区域内显示 */
}

/* 替换原有.intro规则,去掉相对定位偏移,回归正常文档流 */
.intro {
  text-align: center;
  font-size: 50px;
  height: 2000vh;
  padding-top: 30px; /* 可自定义数值,和头部区域拉开间距 */
}

2. 修改视差触发逻辑

替换原有JS代码,增加滚动位置判断,仅在头部区域范围内触发视差位移:

window.addEventListener('scroll', function() {
  const parallax = document.querySelector('.img-background')
  const welcomeSection = document.querySelector('#welcome')
  const welcomeHeight = welcomeSection.offsetHeight
  let scrollPosition = window.pageYOffset;
  
  // 滚动未超出头部区域时正常触发视差
  if (scrollPosition < welcomeHeight) {
    parallax.style.transform = 'translateY(' + scrollPosition * 0.5 + 'px)';
  } else {
    // 超出头部区域后固定背景位置,不再跟随滚动移动
    parallax.style.transform = 'translateY(' + welcomeHeight * 0.5 + 'px)';
  }
});

调整完成后,仅首页头部的视频背景会产生视差滚动效果,页面其余区域将保持普通滚动状态,下方的商品展示内容可正常编写布局,不会和头部区域重叠。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:57:03