MST
星途 面试题库

面试题:CSS过渡与动画:多元素复杂交互动画

假设有一个包含多个图片的画廊,每个图片初始透明度为0.5。当鼠标悬停在画廊区域时,图片透明度变为1,且以不同的动画时长(从1秒到3秒线性递增)和延迟(从0秒到2秒线性递增)依次从左到右放大至1.2倍。请用CSS实现这个效果,阐述你的实现思路并写出核心代码。
24.0万 热度难度
前端开发CSS

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 首先设置画廊容器和图片的基本样式,初始图片透明度设为0.5。
  2. 使用CSS的@keyframes定义图片放大的动画。
  3. 利用nth-child选择器,为每个图片设置不同的动画时长和延迟,实现从1秒到3秒线性递增的动画时长以及从0秒到2秒线性递增的延迟,方向从左到右。
  4. 当鼠标悬停在画廊区域时,通过: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规则。