You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS实现鼠标悬停一张图片时另一张图片持续旋转?

悬停触发另一元素旋转:问题分析与解决方案

核心问题排查

两次尝试均失败的关键原因如下:

  1. 缺失动画关键帧定义:CSS动画必须通过@keyframes指定具体的动画行为,你两次都没写@keyframes rotation,导致动画根本无法执行。
  2. 选择器逻辑错误:你使用逗号分隔的并列选择器(如#image_hov:hover , #image_rot),这表示image_hov悬停时,image_hov自身和image_rot都会触发动画,而非仅让image_rot在image_hov悬停时启动动画。正确的做法是用兄弟选择器关联两个元素的状态。
  3. 第二次尝试中定位设置混乱,可能导致元素位置偏移或重叠,但这不是动画失效的核心原因。

正确实现代码

HTML结构(可保留原有结构,仅调整图片路径为相对路径更规范)

<!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="new.css">
    <title>Hover Trigger Rotation</title>
</head>
<body>
    <span id="bot">
        <div id="chat">
            <img id="image_hov" src="./imgs/hov.png" alt="hover trigger">
            <img id="image_rot" src="./imgs/rot.png" alt="rotating image">
        </div>
    </span>
</body>
</html>

CSS代码(修复选择器、添加关键帧、优化定位)

#chat {
    width: 150px;
    height: 100px;
    position: fixed;
    top: 280px;
    left: 1370px;
    /* 设置为定位容器,让内部绝对定位元素以此为参考 */
    position: relative;
}

#image_hov {
    width: 50px;
    height: 50px;
    position: absolute;
    bottom: 113px;
    right: 29.35px;
    /* 提示用户该元素可交互 */
    cursor: pointer;
}

#image_rot {
    width: 67px;
    height: 67px;
    position: absolute;
    bottom: 104px;
    left: 33px;
}

/* 定义旋转动画的关键帧 */
@keyframes rotation {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

/* 当image_hov悬停时,触发其后的兄弟元素image_rot执行旋转动画 */
#image_hov:hover ~ #image_rot {
    animation: rotation 2s infinite linear;
}

关键说明

  • 用position: absolute替代relative,避免元素位置偏移导致布局混乱,同时让#chat作为定位容器。
  • 兄弟选择器~确保只有当image_hov被悬停时,image_rot才会启动旋转动画。
  • 完整的@keyframes rotation定义了从0度到360度的循环旋转行为。

内容的提问来源于stack exchange,提问作者temper man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 08:54:56