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

Chrome预览中Parallax代码无法运行、不显示的问题求助

修复你的视差效果代码问题

我帮你梳理下代码里的几个关键问题,这些都是导致视差效果无法运行的核心原因:

一、CSS里的语法错误和选择器问题

  • 标签选择器不需要加.,所以.html要改成html,.body改成body;
  • 多处属性后缺少分号(比如height: 100%、max-width: 30px),CSS语法要求属性必须以分号结尾,否则会导致后续样式失效;
  • overflow-x: "Luna"是完全错误的写法,应该改成overflow-x: hidden来禁止横向滚动;
  • transform: tranlasteZ(-1px)拼写错误,正确写法是transform: translateZ(-1px);
  • .image1里的图片路径写错了:url('img/(picture1.jpg')里的括号和引号混乱,应该修正为url('img/picture1.jpg')(确保你的图片确实在img文件夹下);
  • header选择器里的padding 30vw 0 5vw缺冒号,应该是padding: 30vw 0 5vw。

二、HTML和CSS的结构不匹配

你在HTML里用了<div class="header">,但CSS里写的是header标签选择器,两者没有对应上,导致CSS样式无法应用到这个div上。应该把HTML里的<div class="header">改成<header>标签,或者把CSS里的header改成.header类选择器,这里推荐用标签选择器更语义化。

另外,你同时给header:before设置了视差背景,又在header里嵌套了.image1的fixed背景,这会导致视觉混乱,建议保留一种视差实现方式(这里用transform-style: preserve-3d配合translateZ的方式更符合你最初的教程思路)。

三、修正后的完整代码

CSS(style.css)

html {
  height: 100%;
  overflow: hidden;
}

body {
  color: #fff;
  margin: 0;
  padding: 0;
  perspective: 1px;
  transform-style: preserve-3d;
  height: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
}

header {
  box-sizing: border-box;
  min-height: 100vh;
  padding: 30vw 0 5vw;
  position: relative;
  transform-style: inherit;
  width: 100vw;
}

header h1 {
  margin-top: -100px;
}

header, header:before {
  background: 50% 50% / cover;
}

header::before {
  bottom: 0;
  content: "";
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  background-image: url('img/picture1.jpg');
  background-size: cover;
  transform-origin: center center 0;
  transform: translateZ(-1px) scale(2);
  z-index: -1;
  min-height: 100vh;
}

header * {
  font-weight: normal;
  letter-spacing: 0.2em;
  text-align: center;
  margin: 0;
  padding: 1em 0;
}

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Schade's Parallax</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <p>Hi My name is schade I wrote this so I could have a test of my program.</p>
    <!-- 去掉了多余的.image1 div,因为header:before已经实现了视差背景 -->
  </header>
  <!-- 添加测试内容,方便滚动查看视差效果 -->
  <section style="height: 100vh; background: #222; padding: 2em;">
    <h2>滚动看看视差效果</h2>
    <p>当你向下滚动时,header的背景图会比文字滚动得慢,这就是预期的视差效果~</p>
  </section>
</body>
</html>

四、关键原理说明

这个视差效果的核心是利用CSS 3D变换:

  1. 给body设置perspective: 1px,创建一个3D透视空间;
  2. header继承transform-style: preserve-3d,保持3D空间的层级关系;
  3. header::before伪元素通过translateZ(-1px)把背景图“推远”,再用scale(2)放大以填满容器,这样当页面滚动时,背景图的滚动速度会比前景文字慢,从而产生视差效果。

确保你的图片路径正确,然后运行代码就能看到预期的视差效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:08:57