手风琴式折叠卡片展示效果|8月更文挑战

2,084 阅读2分钟

作者:battleKing
仓库:GithubCodePen
博客:CSDN掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权

背景

手风琴式折叠卡片展示效果,一般用于 展示图片、照片、文字 等等。其 主要特点 是:当我们点击任意一张照片时,那张照片像手风琴一样缓缓展开,其他照片像手风琴一样缓缓折叠起来,后续我们还可以向其添加很多各种各样丰富的效果,比如自动轮播、增加3D立体感 ......

最终效果

折叠卡片.gif

一、添加 HTML 文件

  1. 添加一层最外层的 div 命名类名为 box
  2. box 里面添加五个类名为 paneldiv
  3. 在第一个类名为 paneldiv 中添加 active 类名
  4. 每一个类名为 paneldiv 中添加一个 <h3> </h3>
  <div class="box">
    <div class="panel active"">
      <h3>Explore The World</h3>
    </div>
    <div class=" panel">
      <h3>Wild Forest</h3>
    </div>
    <div class="panel">
      <h3>Sunny Beach</h3>
    </div>
    <div class="panel">
      <h3>City on Winter</h3>
    </div>
    <div class="panel">
      <h3>Mountains - Clouds</h3>
    </div>
  </div>

二、添加 CSS 文件

先初始化页面

  1. 设置 *box-sizing: border-box
  2. 设置 body 来使整个项目居中
body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
}

介绍一个随机图库

作用:生产随机假图,用于测试 Lorem Picsum 图库官网全部图片ID

  • 用法
  1. 随机图片 https://picsum.photos/200/300
  2. 防止重复的随机图片 https://picsum.photos/1350/900?random=1
  3. 指定特定的图片 https://picsum.photos/id/237/200/300

主要样式的代码

.box {
  display: flex;
  width: 90vw;
}

.panel {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 80vh;
  border-radius: 50px;
  color: #fff;
  cursor: pointer;
  flex: 0.5;
  margin: 10px;
  position: relative;
  -webkit-transition: all 700ms ease-in;
  transition: all 700ms ease-in;
}
.panel:nth-child(1){
  background-image: url("https://picsum.photos/1350/900?random=1");
}
.panel:nth-child(2){
  background-image: url("https://picsum.photos/1350/900?random=2");
}
.panel:nth-child(3){
  background-image: url("https://picsum.photos/1350/900?random=3");
}
.panel:nth-child(4){
  background-image: url("https://picsum.photos/1350/900?random=4");
}
.panel:nth-child(5){
  background-image: url("https://picsum.photos/1350/900?random=5");
}

.panel h3 {
  font-size: 24px;
  position: absolute;
  bottom: 20px;
  left: 20px;
  margin: 0;
  opacity: 0;
}

.panel.active {
  flex: 5;
}

.panel.active h3 {
  opacity: 1;
  transition: opacity 0.3s ease-in 0.4s;
}

三、添加 JS 文件

主要逻辑

  1. 先获取节点 document.querySelectorAll('.panel')
  2. 通过 forEach 进行遍历,为每一个类名为 pancel 的元素都添加上一个 click事件
  3. 这个事件触发时,又通过forEach 进行遍历,移除全部 pancel 的元素的 active 类名,然后再为 被点击的那个 pancel 元素添上一个 active 类名。
const panels = document.querySelectorAll('.panel')

panels.forEach(panel => {
    panel.addEventListener('click', () => {
        removeActiveClasses()
        panel.classList.add('active')
    })
})

function removeActiveClasses() {
    panels.forEach(panel => {
        panel.classList.remove('active')
    })
}

❤️ 感谢大家

如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。

如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。