在本文中,我们将看到如何创建一个扩展卡片,在点击时显示卡片的扩展视图。为了创建这张卡片,我们将使用 HTML、CSS 和 JavaScript。
方法:在本节中,我们将创建 HTML 卡片的结构。
- 使用类容器创建一个div。
- 在具有 class部分和active的容器内创建另一个div 。
- 使用您选择的背景图像设置div 面板的样式。
- 使用相同的类部分再制作四个div。
HTML:
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')
})
})
HTML
Expanding Cards
CSS:在本节中,我们将使用 CSS 为元素分配常规属性。
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:使用 JavaScript 为每张卡片添加点击功能。 querySelectorAll() 方法用于返回具有类部分的子元素集合。这 添加事件监听器() 方法用于处理每个卡片部分的点击事件。
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')
})
})
完整代码:
HTML
Expanding Cards
输出: