可拓展卡片
引言
github上很火的前端50preject No1 expanding card
-
不废话先放图
-
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="Cards.css">
</head>
<body>
<div class="container">
<div class="panel first active">
<h3>图片1</h3>
</div>
<div class="panel second">
<h3>图片2</h3>
</div>
<div class="panel third">
<h3>图片3</h3>
</div>
<div class="panel fourth">
<h3>图片4</h3>
</div>
<div class="panel fifth">
<h3>图片5</h3>
</div>
</div>
<script src="Cards.js"></script>
</body>
</html>
主要构成就是1个大容器装5个卡槽,卡槽里有个h3标题
- CSS代码
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* 大盒子采用flex布局 大小随视口 本身和内容都居中 */
.container {
display: flex;
width: 90vw;
height: 90vh;
justify-content: center;
align-items: center;
margin: 0 auto;
}
/* 子绝父相为了h3的定位 加过渡使动画不再生硬 flex布局为了与后面的active的flex伸缩因子的值相配合*/
.panel {
position: relative;
height: 80vh;
border-radius: 50px;
margin: 0 5px;
color: rgba(236, 236, 226, 0.747);
flex: 0.5;
transition: all 0.5s ease-in;
}
.panel h3 {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: all 0.7s ease;
}
/* 注意图片是背景图片 */
.first {
background-image: url(images/card1.jpg);
background-position: center;
}
.second {
background-image: url(images/card2.jpg);
background-position: center;
}
.third {
background-image: url(images/card3.jpg);
background-position: center;
}
.fourth {
background-image: url(images/card4.jpg);
background-position: center;
}
.fifth {
background-image: url(images/card5.jpg);
background-position: center;
}
.active.panel h3 {
opacity: 1;
}
/* 动画的实现就是靠伸缩因子的值的变化 active表示被点击的卡槽 */
.active {
flex: 5;
margin: 0 30px;
}
-
js代码
const panels = document.querySelectorAll('.panel'); var lock = true; panels.forEach(panel => { panel.addEventListener('click', () => { if (!lock) return; removeActiveClasses(); panel.classList.add('active'); lock = false; setTimeout(() => { lock = true; }, 500); }) }) function removeActiveClasses() { panels.forEach(panel => { panel.classList.remove('active'); }) }
基本思路是为panel加一个事件监听,一个卡槽被点击后,先将所有的卡槽的active类去掉,然后再为点击对的panel加上active类,而且防止用户点击过快导致动画被中断,加入了一个函数节流锁。
-
函数节流模板
// 声明节流锁 var lock = true; function 需要节流的函数() { // 如果锁是关闭状态,则不执行 if (!lock) { return; } // 函数核心语句 // …… // 函数核心语句 // 关锁 lock = false; // 指定毫秒数后将锁打开 setTimeout(function() { lock = true; }, 2000); }
函数核心语句
// 关锁
lock = false;
// 指定毫秒数后将锁打开
setTimeout(function() {
lock = true;
}, 2000);
}