朱纯树博客
VPS测评推荐网站
cloudacead cloudacead

滚动视差让你不相信“眼见为实”

safar-safarov-MSN8TFhJ0is-unsplash (1).jpg

引言

视差滚动(Parallax Scrolling)是指让多层背景以不同的速度移动,形成立体的运动效果。

其实,这项技术早在 2013 年就已经开始在一些国外的网站中得到了大量的应用。由于它给网站带来了非常出色的视觉体验,现在已经有数不胜数的网站应用了这项技术。

我是在最近的项目中用到了这块,觉得有必要整理一下。本文主要是简单的介绍一下什么是视差滚动,实现方式以及如何在现有框架(vue/react)中使用视差滚动。

什么是视差滚动?

视差效果, 最初是一个天文术语。当我们看着繁星点点的天空时,较远的恒星运动较慢,而较近的恒星运动较快。当我们坐在车里看着窗外时,我们会有相同的感觉。远处的山脉似乎没有动,附近的稻田很快过去了。许多游戏使用视差效果来增加场景的三维度。说的简单点就是,滚动屏幕时,网页中元素的位置会发生变化。但是不同的元素位置变化的速度不同,导致网页中产生分层元素的错觉。

看完上面这段,相信你对视差滚动的概念已经有了一个初步的了解。下面让我们先来看一下如何用 css 来实现视差滚动。

css 实现

css 中主要有两种实现方式:分别是通过background-attachment: fixedtransform: translate3d来实现,下面让我们看一下具体的实现方式:

background-attachment: fixed

平时业务开发中可能不太会用到background-attachment,让我们先来认识一下它。

background-attachment CSS 属性决定背景图像的位置是在视口内固定,还是随着包含它的区块滚动。

它一共有三个属性:

  • fixed: 键字表示背景相对于视口固定。即使一个元素拥有滚动机制,背景也不会随着元素的内容滚动。
  • local: 此关键字表示背景相对于元素的内容固定。如果一个元素拥有滚动机制,背景将会随着元素的内容滚动。
  • scroll: 此关键字表示背景相对于元素本身固定, 而不是随着它的内容滚动。我们使用 background-attachment: fixed 来实现视差滚动,看一下示例:
// HTML
<div class="a-text">1</div>
<div class="a-img1">2</div>
<div class="a-text">3</div>
<div class="a-img2">4</div>
<div class="a-text">5</div>
<div class="a-img3">6</div>
<div class="a-text">7</div>
// css
$img1: 'https://images.pexels.com/photos/1097491/pexels-photo-1097491.jpeg';

$img2: 'https://images.pexels.com/photos/2437299/pexels-photo-2437299.jpeg';

$img3: 'https://images.pexels.com/photos/1005417/pexels-photo-1005417.jpeg';

div {
    height: 100vh;
    background: rgba(0, 0, 0, .7);
    color: #fff;
    line-height: 100vh;
    text-align: center;
    font-size: 20vh;
}

.a-img1 {
    background-image: url($img1);
    background-attachment: fixed;
    background-size: cover;
    background-position: center center;
}

.a-img2 {
    background-image: url($img2);
    background-attachment: fixed;
    background-size: cover;
    background-position: center center;
}

.a-img3 {
    background-image: url($img3);
    background-attachment: fixed;
    background-size: cover;
    background-position: center center;
}

效果如下:

img

当然,你可以直接去这里查看:https://codepen.io/jack-cool/pen/MWYogYQ

transform: translate3d

同样,让我们先来看一下两个概念transformperspective

  • transform: css3 属性,可以对元素进行变换(2d/3d),包括平移 translate,旋转 rotate,缩放 scale,等等
  • perspective: css3 属性,当元素涉及 3d 变换时,perspective 可以定义我们眼睛看到的 3d 立体效果,即空间感。

先来看一下示例:

// html
<div id="app">
   <div class="one">one</div>
   <div class="two">two</div>
   <div class="three">three</div>
 </div>
// css
html {
   overflow: hidden;
   height: 100%
}

 body {
   perspective: 1px;
   transform-style: preserve-3d;
   height: 100%;
   overflow-y: scroll;
   overflow-x: hidden;
 }
 #app{
   width: 100vw;
   height:200vh;
   background:skyblue;
   padding-top:100px;
 }
.one{
  width:500px;
  height:200px;
  background:#409eff;
  transform: translateZ(0px);
  margin-bottom: 50px;
}
.two{
  width:500px;
  height:200px;
  background:#67c23a;
  transform: translateZ(-1px);
  margin-bottom: 150px;
}
.three{
  width:500px;
  height:200px;
  background:#e6a23c;
  transform: translateZ(-2px);
  margin-bottom: 150px;
}

效果如下:

img

当然,你可以直接去这里查看:https://codepen.io/jack-cool/pen/zYxzOpb

这里解释下使用transform: translate3d来实现视差滚动的原理:

1、给容器设置上transform-style: preserve-3dperspective: xpx,那么处于这个容器下的子元素就会处于 3D 空间中;

2、给子元素分别设置不同的transform: translateZ(),这时不同子元素在 3D Z 轴方向距离屏幕的距离也就不一样;

3、滚动滚动条,由于子元素设置了不同的transform: translateZ(),那么他们滚动的上下距离translateY相对屏幕(我们的眼睛),也是不一样的,这就达到了滚动视差的效果。

总结下来就是: 父容器设置transform-style: preserve-3dperspective: xpx,子元素设置不同的transform: translateZ()

看完了用 css 实现滚动视差的两种方式,下面让我们看下如何在现有框架(vue/react)中来应用滚动视差。

vue 或 react 中使用

react 中使用

在 react 中使用可以采用react-parallax,代码示例:

import React from "react";
import { render } from "react-dom";
import { Parallax } from "react-parallax";
import Introduction from "./Introduction";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};
const insideStyles = {
  background: "white",
  padding: 20,
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%,-50%)"
};
const image1 =
  "https://images.pexels.com/photos/830891/pexels-photo-830891.jpeg";
const image2 =
  "https://images.pexels.com/photos/1236701/pexels-photo-1236701.jpeg";
const image3 =
  "https://images.pexels.com/photos/3210189/pexels-photo-3210189.jpeg";
const image4 =
  "https://images.pexels.com/photos/2437299/pexels-photo-2437299.jpeg";

const App = () => (
  <div style={styles}>
    <Introduction name="React Parallax" />
    <Parallax bgImage={image1} strength={500}>
      <div style={{ height: 500 }}>
        <div style={insideStyles}>HTML inside the parallax</div>
      </div>
    </Parallax>
    <h1>| | |</h1>
    <Parallax bgImage={image3} blur={{ min: -1, max: 3 }}>
      <div style={{ height: 500 }}>
        <div style={insideStyles}>Dynamic Blur</div>
      </div>
    </Parallax>
    <h1>| | |</h1>
    <Parallax bgImage={image2} strength={-100}>
      <div style={{ height: 500 }}>
        <div style={insideStyles}>Reverse direction</div>
      </div>
    </Parallax>
    <h1>| | |</h1>
    <Parallax
      bgImage={image4}
      strength={200}
      renderLayer={percentage => (
        <div>
          <div
            style={{
              position: "absolute",
              background: `rgba(255, 125, 0, ${percentage * 1})`,
              left: "50%",
              top: "50%",
              borderRadius: "50%",
              transform: "translate(-50%,-50%)",
              width: percentage * 500,
              height: percentage * 500
            }}
          />
        </div>
      )}
    >
      <div style={{ height: 500 }}>
        <div style={insideStyles}>renderProp</div>
      </div>
    </Parallax>
    <div style={{ height: 500 }} />
    <h2>{"\u2728"}</h2>
  </div>
);

render(<App />, document.getElementById("root"));

效果如下:

img

当然,更多细节可以查看:https://codesandbox.io/s/react-parallax-zw5go

vue 中使用

在 vue 中使用可以采用vue-parallaxy,代码示例:

<template>
  <div id="app">
    <div style="background-color: #fff; height: 100vh;">
      <h1 style="margin-top: 0; padding-top: 20px;">Scroll down ⬇</h1>
    </div>
    <div style="position: relative; z-index: 9999; background-color: #fff;">
      <h1 style="margin:0;">Parallax Effect</h1>
      <parallax>
        <img src="https://images.pexels.com/photos/830891/pexels-photo-830891.jpeg">
      </parallax>
    </div>
    <div style="background-color: #fff; height: 100vh;"></div>
    <h1>Parallax fixed position</h1>

    <div style="position: relative;">
      <parallax :fixed="true">
        <img src="https://images.pexels.com/photos/3210189/pexels-photo-3210189.jpeg">
      </parallax>
    </div>

    <div style="background-color: #fff; height: 100vh;"></div>
  </div>
</template>

<script>
import Parallax from "vue-parallaxy";

export default {
  name: "App",
  components: {
    Parallax
  }
};
</script>

<style>
body {
  margin: 0;
}
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  position: relative;
}
</style>

效果如下:

img

当然,更多细节可以查看: https://codesandbox.io/s/vue-parallaxjs-ljh9g

本文分享自微信公众号 – 前端森林(gh_108ded952c4c),作者:前端森林

赞(1) 打赏
未经允许不得转载:VPS测评推荐网站 - 朱纯树博客 » 滚动视差让你不相信“眼见为实”

评论 30

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #30

    Great article. I will be dealing with a few of these issues as well..

  2. #29

    Heya i’m for the primary time here. I found this board and I in finding It truly helpful &
    it helped me out a lot. I’m hoping to provide something again and aid others such as you helped me.

  3. #28

    Valuable information. Fortunate me I discovered your site accidentally,
    and I am shocked why this coincidence didn’t came about earlier!
    I bookmarked it.

  4. #27

    Quality posts is the key to interest the users to pay a quick visit the web page,
    that’s what this web page is providing.

    tinyurl.com1周前 (08-03)回复
  5. #26

    I absolutely love your blog and find many of your post’s to be
    just what I’m looking for. Do you offer guest writers to write content in your case?
    I wouldn’t mind producing a post or elaborating on a few of the subjects you write regarding
    here. Again, awesome site!

    tinyurl.com2周前 (07-28)回复
  6. #25

    I read this post fully regarding the comparison of most up-to-date and preceding technologies,
    it’s remarkable article.

  7. #24

    Hi there, I want to subscribe for this web site to take most up-to-date updates, so where can i do it
    please assist.

  8. #23

    What’s up all, here every one is sharing these know-how,
    so it’s good to read this blog, and I used to go to see this webpage every day.

    tinyurl.com2个月前 (06-12)回复
  9. #22

    Really no matter if someone doesn’t know after that
    its up to other viewers that they will assist, so here it takes place.

    http://tinyurl.com/2个月前 (06-12)回复
  10. #21

    I am sure this piece of writing has touched all the internet visitors, its really really good article on building up new webpage.

    tinyurl.com2个月前 (06-11)回复
  11. #20

    Good day! This is my first comment here so I just wanted
    to give a quick shout out and say I truly enjoy reading
    through your blog posts. Can you suggest any other blogs/websites/forums that
    cover the same topics? Thanks for your time!

  12. #19

    You’re so interesting! I don’t suppose I’ve truly read through something like this before.
    So wonderful to find somebody with a few genuine thoughts on this subject.
    Really.. thanks for starting this up. This site is one thing that is needed on the web, someone with
    a bit of originality!

  13. #18

    What’s up to every one, the contents present at this web site are really remarkable for people experience, well, keep
    up the good work fellows.

    tinyurl.com3个月前 (05-16)回复
  14. #17

    This is a very good tip particularly to those fresh to the blogosphere.

    Brief but very precise information… Appreciate your sharing this
    one. A must read article!

  15. #16

    Hi to every body, it’s my first visit of this webpage;
    this web site includes awesome and really good data designed for visitors.

    tinyurl.com3个月前 (05-10)回复