演示地址
Expanding Cards (50projects50days.com)
实现思路
结构样式方面主要是flex弹性布局,并且添加过渡效果。
js部分首先获取所有box节点然后遍历添加click事件,添加、移除active来实现切换效果。
代码
html结构
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>扩展卡片</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="box active" style="background-image: url('./image/1.jpg')">
<h3>人间四月芳菲尽,山寺桃花始盛开。</h3>
</div>
<div class="box" style="background-image: url('./image/2.jpg')">
<h3>重湖叠巘清嘉,有三秋桂子,十里荷花。</h3>
</div>
<div class="box" style="background-image: url('./image/3.jpg')">
<h3>月落乌啼霜满天,江枫渔火对愁眠。</h3>
</div>
<div class="box" style="background-image: url('./image/4.jpg')">
<h3>天寒霜雪繁,游子有所之。</h3>
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
css样式
* {
box-sizing: border-box;
}
body {
/* 弹性布局垂直居中 */
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f8f1e7;
}
.container {
display: flex;
width: 90vw;
}
.box {
/* 子元素绝对定位,父元素相对定位 */
position: relative;
/* flex元素在主轴上的比例 */
flex: 0.5;
height: 80vh;
margin: 10px;
border-radius: 50px;
box-shadow: 1px 2px 10px 0px #b7b7b7;
/* 调整背景图片 */
background-size: cover;
background-position: center;
background-repeat: no-repeat;
color: #fff;
cursor: pointer;
/* 过渡效果 */
transition: flex 0.8s ease-in;
}
.box h3 {
/* 绝对定位 */
position: absolute;
right: 20px;
bottom: 20px;
margin: 0;
font-size: 28px;
opacity: 0;
transition: opacity 0.2s ease-in 0.4s;
}
.active {
/* 增加元素在主轴上的比例 */
flex: 5;
}
.active h3 {
opacity: 1;
}
js行为
// 查询所有.box节点
const nodes = document.querySelectorAll('.box');
// console.log(nodes);
// 遍历添加click事件
nodes.forEach(node => {
node.addEventListener('click', () => {
removeActiveClassses();
// 给当前对象添加acticve
node.classList.add('active');
})
});
// 移除所有节点active
function removeActiveClassses() {
nodes.forEach(node => {
node.classList.remove('active');
})
}
参考资料:50 Projects 50 Days | Traversy Media
50 unique mini-projects to sharpen your HTML, CSS & JavaScript skills
网友评论