“拉开窗帘”就是背景在滚动时从暗变为亮,而顶部的内容在处于粘性位置时也会从亮变为暗。

展示效果如图:

 下面用简介明了的代码来给大家介绍这个效果

首先是HTML部分:

类名 curtain是帘,窗帘的意思

类名invert是反转的意思

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Open the curtain effect 拉起窗帘效果</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <!-- 
        拉开窗帘效果:即背景在滚动时从暗变为亮,而顶部的内容在处于粘性位置时也会从亮变为暗
        这里仅用HTML和CSS来展示
     -->
    <div class="curtain">
        <div class="invert">
          <h2>拉起窗帘效果</h2>
        </div>
    </div>
</body>
</html>

下面是css代码部分:

/* 
这是css变量,可以修改的
minh:容器高度
color1:浅色
color2:深色
*/
:root {
  --minh: 98vh;   
  --color1: skyblue;
  --color2: pink;
}

/* 
  Alinear-gradient代表“分裂”背景
  min-height容器底部的额外空间 
  使用::after伪元素将额外的空间添加到底部。这样,我们的“粘性”内容实际上会在滚动经过::after元素时粘在容器上。
*/
.curtain {
  /* create the "split" background */
  background-image: linear-gradient(to bottom, var(--color2) 50%, var(--color1) 50%);
}

/* add extra space to the bottom (need this for the "sticky" effect) */
.curtain::after {
  content: "";
  display: block;
  min-height: var(--minh);
}


.invert {
  /* make the content sticky */
  position: sticky;
  top: 20px;

  /* blend the content with the contrast effect */
  mix-blend-mode: difference;

  /* center the content */
  display: flex;
  align-items: center;
  justify-content: center;
  
  /* set the minimum height of the section */
  min-height: var(--minh);
}

h2 {
  /* set the color of the text */
  color: var(--color1);
}

上面就是“拉开窗帘”效果的代码了,有兴趣的朋友可以直接复制过去运行看看效果,也可以自行修改里面的内容,看看不同的效果。

上面展示的只是简单的效果,添加其他因素还可以变得更加有趣。

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐