background-attachment 实现背景图滚动视觉差

2023-11-07  本文已影响0人  小李不小

当滚动鼠标滑轮的时候,各个图层以不同的速度移动,形成视觉差的效果

background-attachment

作用是设置背景图像是否固定或者随着页面的其余部分滚动

值分别有如下:

也就是说,背景一开始就已经被固定在初始的位置

核心的css代码如下:

section {
    height: 100vh;
}

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

//background-attachment设置背景图像是否固定或者随着页面的其余部分滚动。

整体例子如下:

<!DOCTYPE html>
<html>
<head>
    <title></title>
<style>
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(https://images.pexels.com/photos/1097491/pexels-photo-1097491.jpeg);
            background-attachment: fixed;
            background-size: cover;
            background-position: center center;
        }

        .a-img2 {
            background-image: url(https://images.pexels.com/photos/2437299/pexels-photo-2437299.jpeg);
            background-attachment: fixed;
            background-size: cover;
            background-position: center center;
        }

        .a-img3 {
            background-image: url(https://images.pexels.com/photos/1005417/pexels-photo-1005417.jpeg);
            background-attachment: fixed;
            background-size: cover;
            background-position: center center;
        }
</style>
</head>
<body>

    <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>

<script type="text/javascript">

  </script>
</body>
</html>


效果图

image.png
上一篇 下一篇

猜你喜欢

热点阅读