4

background-attachment实现滚动阴影效果

 3 years ago
source link: https://www.haorooms.com/post/background_attachment
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

background-attachment实现滚动阴影效果

2021年3月12日 416次浏览

之前文章视觉差效果制作,用到了background-attachment,今天用background-attachment实现滚动阴影效果。

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

简单而言,就是决定了在可滚动的容器中,背景图案是如何进行运动的。通过两个简单的 Demo,弄懂 background-attachment: srcoll 和 background-attachment: local。

background-attachment: local,这个就是和我们日常使用中的用法是一致的,可滚动容器的背景图案随着容器进行滚动:

enter image description here

background-attachment: scroll,这个是今天的主角,它表明背景相对于元素本身固定, 而不是随着它的内容滚动:

enter image description here

srcoll 与 local 同时使用,实现障眼法

到这里,可能很多同学还是懵的,我们到底要做什么呢?这个和本文的滚动阴影有什么关联呢?

别急,滚动阴影的难点在于,初始没有滚动的时候是没有阴影展现的,只有当开始滚动,阴影才会出现。

所以这里,我们借助 background-attachment: srcoll 和 background-attachment: local 两个属性,在滚动初始的时候,利用两层背景叠加在一起隐藏阴影背景,真正滚动的时候,将叠加的部分移走,只漏出阴影部分即可。

我们用给滚动容器,加上两个渐变效果,分别运用上 background-attachment: srcoll 和 background-attachment: local,再叠加起来,像是这样:

<!-- 可滚动容器 -->
<ul> 
    <li>...</li>
    ...
    <li>...</li>
</ul> 
// 情形一:
.g-one {
    background: linear-gradient(#fff, #f00);
    background-size: 100% 10px;
    background-repeat: no-repeat;
    background-attachment: local;
}

// 情形二:
.g-two {
    background: radial-gradient(at 50% 0, #000, #0f0 70%);
    background-size: 100% 10px;
    background-repeat: no-repeat;
    background-attachment: scroll;
}

// 情形三:
.g-combine {
    background: 
        linear-gradient(#fff, #f00),
        radial-gradient(at 50% 0%, #000, #0f0 70%);
    background-size: 100% 10px, 100% 10px;
    background-repeat: no-repeat;
    background-attachment: local, scroll;
}

实际效果就是这样,一个背景是随容器滚动,一个背景是随容器固定。随容器滚动的背景充当初始的遮罩层:

enter image description here

可以看到,当滚动的时候,最后一幅叠加的情况,其实就是我们需要的滚动的时候展示不同的颜色(阴影)的效果。我们调整一下两个渐变的颜色,遮罩层(background-attachment: local)为白色,再把固定不动的阴影层(background-attachment: scroll),利用径向渐变模拟为我们想要的阴影颜色。

CSS 代码大概是这样:

.g-final {
    background: 
        linear-gradient(#fff, transparent 100%),
        linear-gradient(rgba(0, 0, 0, .5), transparent 100%);
    background-size: 100% 50px, 100% 10px;
    background-repeat: no-repeat;
    background-attachment: local, scroll;
}

利用 linear-gradient(rgba(0, 0, 0, .5), transparent 100%) 线性渐变模拟了一层灰色阴影:

enter image description here

这样就实现了如下图,css滚动阴影的效果

enter image description here


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK