面试题答案
一键面试实现思路
- 首先设置画廊容器和图片的基本样式,初始图片透明度设为0.5。
- 使用CSS的
@keyframes
定义图片放大的动画。 - 利用
nth-child
选择器,为每个图片设置不同的动画时长和延迟,实现从1秒到3秒线性递增的动画时长以及从0秒到2秒线性递增的延迟,方向从左到右。 - 当鼠标悬停在画廊区域时,通过
:hover
伪类改变图片透明度为1,并应用放大动画。
核心代码
/* 画廊容器样式 */
.gallery {
display: flex;
gap: 20px;
}
/* 图片初始样式 */
.gallery img {
opacity: 0.5;
transition: opacity 0.3s ease;
}
/* 定义放大动画 */
@keyframes scale-up {
from {
transform: scale(1);
}
to {
transform: scale(1.2);
}
}
/* 鼠标悬停在画廊区域时的图片样式 */
.gallery:hover img {
opacity: 1;
}
/* 为每个图片设置不同的动画时长和延迟 */
.gallery img:nth-child(1) {
animation: scale-up 1s ease forwards;
animation-delay: 0s;
}
.gallery img:nth-child(2) {
animation: scale-up 1.5s ease forwards;
animation-delay: 0.5s;
}
.gallery img:nth-child(3) {
animation: scale-up 2s ease forwards;
animation-delay: 1s;
}
.gallery img:nth-child(4) {
animation: scale-up 2.5s ease forwards;
animation-delay: 1.5s;
}
.gallery img:nth-child(5) {
animation: scale-up 3s ease forwards;
animation-delay: 2s;
}
上述代码假设画廊容器的类名为gallery
,实际应用中可根据具体情况调整。并且这里只展示了5张图片的情况,如需更多图片,可按照规律继续添加nth-child
规则。