css实现滚动视差,贼拉酷炫哟~

视差滚动(Parallax Scrolling)就是指让多层背景以不同的速度移动,形成立体的运动效果,带来非常出色的视觉体验。 作为网页设计的热点趋势,越来越多的网站应用了这项技术。通常而言,滚动视差在前端需要辅助 Javascript 才能实现。当然,其实 CSS 在实现滚动视差效果方面,也有着不俗的能力。

今天主要用的属性为:background-attachment

就是说如果指定了 background-image ,那么 background-attachment 决定背景是在视口中固定的还是随着包含它的区块滚动的。

参数:scroll,local,fixed

background-attachment: scroll

scroll 此关键字表示背景相对于元素本身固定, 而不是随着它的内容滚动。

background-attachment: local

local 此关键字表示背景相对于元素的内容固定。如果一个元素拥有滚动机制,背景将会随着元素的内容滚动, 并且背景的绘制区域和定位区域是相对于可滚动的区域而不是包含他们的边框。

background-attachment: fixed

fixed 此关键字表示背景相对于视口固定。即使一个元素拥有滚动机制,背景也不会随着元素的内容滚动。

在这里我们使用图文混合排布的方式,实现滚动视差,HTML 结构如下,.g-word 表示内容结构,.g-img 表示背景图片结构:

<section class="g-word">Header</section>
<section class="g-img">IMG1</section>
<section class="g-word">Content1</section>
<section class="g-img">IMG2</section>
<section class="g-word">Content2</section>
<section class="g-img">IMG3</section>
<section class="g-word">Footer</section>

css样式

section {
    height: 100vh;
}

.g-img {
    background-image: url(...);
    background-attachment: fixed;
    background-size: cover;
    background-position: center center;
}

我们把上面 background-attachment: fixed 注释掉,或者改为 background-attachment: local,再看看效果:

这次,图片正常跟随滚动条滚动了,按常理,这种效果才符合我们大脑的思维。

而滚动视差效果,正是不按常理出牌的一个效果,重点来了:

当页面滚动到图片应该出现的位置,被设置了 background-attachment: fixed 的图片并不会继续跟随页面的滚动而跟随上下移动,而是相对于视口固定死了。

好,我们再来试一下,如果把所有 .g-word 内容区块都去掉,只剩下全部设置了 background-attachment: fixed 的背景图区块,会是怎么样呢?

<section class="g-img">IMG1</section>
<section class="g-img">IMG2</section>
<section class="g-img">IMG3</section>
section {
    height: 100vh;
}

.g-img {
    background-image: url(...);
    background-attachment: fixed;
    background-size: cover;
    background-position: center center;
}

就是 CSS 使用 background-attachment: fixed 实现滚动视差的一种方式,也是相对而言比较容易的一种。当然,background-attachment: fixed 本身的效果并不仅只是能有用来实现滚动视差效果,合理运用,还可以实现其他很多有趣的效果。

例如:实现图片点击水纹效果,滚动视差文字阴影/虚影效果

参考自:weixin/筑梦前端

如有侵权请联系删除

猜你喜欢

转载自blog.csdn.net/qq_42451932/article/details/85872117