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

如何在带叠加层的封面图片上实现无JS视差效果?

实现封面图片视差及main滚动覆盖效果

你之前的问题在于 background-attachment: fixed 是元素背景图片专属属性,对<img>标签完全无效,下面提供两种可行方案:

方案一:将图片改为背景图实现视差

把图片转为.cover的背景图,直接利用background-attachment: fixed实现视差,同时调整封面高度保证内容展示:

修改后的HTML

<div class='wrapper'>
  <div class='cover'>
    <div class='cover_wrapper'>
      <h1 class='title font'>Title</h1>
      <p class='font' style='padding-top: 140px;margin: 0px;'>This is my Website</p>
    </div>
  </div>
</div>

<div id='main' role='main'>
  something something
</div>

修改后的CSS

* {
  box-sizing: border-box;
}

body{
  padding: 0;
  margin: 0;
}

.wrapper {
  position: relative;
}

@media (min-width: 80em){
  .cover_wrapper {
    max-width: 1280px;
  }
}

.cover {
  position: relative;
  margin-bottom: 2em;
  padding: 8em 0; /* 增加内边距提升封面高度 */
  clear: both;
  background-image: url('https://images.unsplash.com/photo-1514496959998-c01c40915c5f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 75% 50%;
  background-attachment: fixed; /* 视差核心属性 */
  -webkit-animation: intro 0.3s both;
  animation: intro 0.3s both;
  animation-delay: 0s;
  -webkit-animation-delay: 0.25s;
  animation-delay: 0.25s;
}

.cover::after{
  clear: both;
  content: '';
  display: table;
}

.title {
  font-size: 2.441em;
  margin-top: 0;
  line-height: 1;
  margin: 2em 0 0.5em;
}

.cover_wrapper {
  padding-left: 1em;
  padding-right: 1em;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  box-sizing: border-box;
}

.font{
  font-family: -apple-system, BlinkMacSystemFont, 'Roboto', 'Segoe UI', 'Helvetica Neue', 'Lucida Grande', Arial, sans-serif;
  font-size: 1.25em;
  color: #fff;
  text-shadow: 1px 1px 4px rgba(0, 0, 0, 0.5);
}

#main {
  background-color: #fff; /* 设置背景色,滚动时覆盖图片 */
  padding: 2em;
  min-height: 100vh; /* 保证main足够长,方便测试滚动 */
}

方案二:保留<img>标签,用固定定位实现

给<img>设置position: fixed固定在视口底层,通过调整容器高度和main的背景色实现覆盖效果:

修改后的CSS(仅列关键修改部分)

.wrapper {
  position: relative;
  height: 500px; /* 定义封面区域高度 */
}

.img {
  position: fixed; /* 固定在视口,实现视差 */
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  object-fit: cover;
  margin: 0;
  z-index: -1; /* 置于内容下方 */
}

.cover {
  position: relative;
  margin-bottom: 2em;
  padding: 8em 0;
  clear: both;
  background-color: rgba(0,0,0,0.2); /* 可选:增加文字可读性 */
  -webkit-animation: intro 0.3s both;
  animation: intro 0.3s both;
  animation-delay: 0s;
  -webkit-animation-delay: 0.25s;
  animation-delay: 0.25s;
}

#main {
  background-color: #fff;
  padding: 2em;
  min-height: 100vh;
}

两种方案任选其一即可,方案一更简洁,方案二更适合需要动态修改图片的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:24:58