如何使用HTML、CSS和Javascript创建可扩展卡片
在本文中,我们将看到如何创建一个可扩展的卡片,点击时显示卡片的展开视图。为了创建这个卡片,我们将使用HTML、CSS和Javascript。
方法: 在这个部分,我们将创建HTML卡片的结构。
- 创建一个带有类名为container的div。
- 在container中创建另一个带有类名为section和active的div。
- 用你选择的背景图像来设置div面板的样式。
- 再创建另外四个类名为section的div。
HTML: 在这个部分,我们将创建文件的基本结构。
CSS: 在这个部分,我们将使用CSS为元素分配一般属性。
Javascript: 使用Javascript为每个卡片添加点击功能。使用querySelectorAll()方法来返回带有类名为section的子元素的集合。使用addEventListener()方法来处理每个卡片部分的点击事件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Expanding Cards</title>
</head>
<body>
<!-- Container -->
<div class="container">
<!-- Div with section and active -->
<div class="section one active"></div>
<!-- All another div with section -->
<div class="section two"></div>
<div class="section three"></div>
<div class="section four"></div>
</div>
</body>
</html>
CSS代码
/* Setting container to flex and width to 80% of view port */
.container{
display: flex;
width: 80%;
}
/*Adding background image to each section*/
.one{
background: url(img/one.jpg);
}
.two{
background: url(img/two.jpg);
}
.three{
background: url(img/three.jpg);
}
.four{
background: url(img/four.jpg);
}
/* Background properties and transition effect to section */
.section{
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 80vh;
cursor: pointer;
flex: 0.2;
margin:8px;
position: relative;
transition: all 0.7s ease-out;
}
/* section with active class will grow flex to 3 times */
.section.active{
flex: 3;
}
JavaScript代码
// Selecting all sections with class of section
const sections = document.querySelectorAll('.section')
// On click event for each section
sections.forEach((section)=>{
section.addEventListener('click',()=>{
// remove active class from all another section
// and add it to the selected section
sections.forEach((section) => {
section.classList.remove('active')
})
section.classList.add('active')
})
})
输出:

极客教程