第一天:扩展卡片
学了很久前端,总是感觉基础不踏实,知识过段时间就忘记了。于是准备完成github上面的50projects50days这个项目。
github链接:github.com/bradtravers…
实现效果如下:
1.HTML
html这部分比较简单,整5个div就行了,图片是我从米哈游官网复制的链接,所以直接贴代码了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css">
<title>01-My-expanding-cards</title>
</head>
<body>
<div class="container">
<div class="panel active" style="background-image: url('https://uploadstatic.mihoyo.com/contentweb/20200103/2020010311083818450.png')">
<h3>可莉</h3>
</div>
<div class="panel" style="background-image: url('https://uploadstatic.mihoyo.com/contentweb/20200315/2020031516372312969.png')">
<h3>香菱</h3>
</div>
<div class="panel" style="background-image: url('https://uploadstatic.mihoyo.com/contentweb/20200828/2020082814270362598.png')">
<h3>七七</h3>
</div>
<div class="panel" style="background-image: url('https://uploadstatic.mihoyo.com/contentweb/20210105/2021010519112015673.png')">
<h3>甘雨</h3>
</div>
<div class="panel" style="background-image: url('https://uploadstatic.mihoyo.com/contentweb/20210720/2021072011090118454.png')">
<h3>神里绫华</h3>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
2.CSS
实现扩展卡片的关键在于CSS属性的设置,默认第一个div为active,设置panel为卡片折叠的状态,而active为卡片展开的状态,再用JS添加点击事件,每次点击对应panel,将其属性设置为active即可实现功能。通过增/删active属性来实现缩放。
@import url('https://fonts.googleapis.com/css?family=Muli&display=swap');
*{
box-sizing: border-box;
}
body{
font-family: 'Muli', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
margin: 0;
background-image:url('https://webstatic.mihoyo.com/upload/static-resource/2021/12/19/f3f88c240425bb5595a5810b08a5be60_2620021836011252967.jpg');
}
.container{
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;
-webkit-filter: blur(3px); /* Chrome, Opera */
-moz-filter: blur(3px);
-ms-filter: blur(3px);
filter: blur(3px);
}
.panel h3 {
font-size: 24px;
position: absolute;
bottom: 20px;
left: 20px;
margin: 0;
opacity: 0;
}
.panel.active{
flex: 5;
-webkit-filter: blur(0px); /* Chrome, Opera */
-moz-filter: blur(0px);
-ms-filter: blur(0px);
filter: blur(0px);
}
.panel.active h3{
opacity: 1;
transition: opacity 0.3s ease-in 0.4s;
}
@media (max-width: 480px) {
.container {
width: 100vw;
}
.panel:nth-of-type(4),
.panel:nth-of-type(5) {
display: none;
}
}
3.JavaScript
思路:选中所有panels,为所有panel添加点击事件,当点击时,清楚所有panel的active类属性,并且为当前点击的panel添加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')
})
}
然后就大功告成啦!