概述

  • 利用 perspective + translateZ + scale 创建CSS视差;容器滚动,子层不同Z深度移动速度不同。
  • 相关:overflow与height auto

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body style="overflow: hidden">
    <div
      id="app"
      style="
        perspective: 1px; /* 越小,透视效果越明显  */
        transform-style: preserve-3d; /* 只能影响直接的子元素,使其受透视影响 */
        height: 100vh; /* 要保证内容在app容器中溢出, 使其能够滚动 */
        overflow-y: scroll;
      "
    >
      <div
        class="parallax-layer"
        style="
          transform: translateZ(-2px) scale(3); /* 元素的距离越远,移动越慢;scale可以弥补透视造成的大小变化 */
          width: 500px;
          height: 1000px;
          background-color: #409eff;
        "
      ></div>
      <div
        class="parallax-layer"
        style="
          transform: translateZ(-1px) scale(2);
          width: 400px;
          height: 1000px;
          background-color: #67c23a;
        "
      ></div>
      <div
        class="parallax-layer"
        style="
          transform: translateZ(0) scale(1);
          width: 300px;
          height: 1000px;
          background-color: #e6a23c;
        "
      ></div>
    </div>
  </body>
</html>