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

鼠标事件触发CSS动画异常:PC端Chrome不生效问题求助

问题解决:Mouseover触发CSS动画在PC Chrome失效且Mouseout自动触发

问题根源

动画启动后,元素通过transform: translateX发生位移,鼠标位置不再覆盖元素的新位置,导致mouseout事件立即触发,将animation设为none,因此PC Chrome中看不到动画效果。Firefox及移动端Chrome因事件触发机制或元素命中检测的差异,暂时表现正常,但本质存在相同逻辑问题。


方案1:使用CSS:hover实现(推荐)

直接通过CSS伪类绑定动画,无需JS,彻底避免事件触发异常,所有浏览器表现一致。

修改后的CSS代码:

.circ {
  pointer-events: all;
}
.rect {
  pointer-events: none;
}
@keyframes move {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(500px);
  }
}
/* 鼠标悬停时触发动画 */
.circ:hover {
  animation: move 1000ms infinite ease-in-out alternate;
}

说明:移除原JS代码即可,鼠标悬停在圆形元素上时自动播放动画,离开时停止。


方案2:JS事件绑定到父容器

若必须用JS控制,将事件绑定到元素的父容器(如.crcl),确保元素移动后鼠标仍在容器范围内,不会提前触发mouseout。

修改后的JS代码:

const container = document.querySelector('.crcl');
const element = document.querySelector('.circ');

container.addEventListener('mouseenter', function() {
  console.log(1);
  element.style.animation = "move 1000ms infinite ease-in-out alternate";
});

container.addEventListener('mouseleave', function() {
  console.log(2);
  element.style.animation = "none";
});

说明:使用mouseenter/mouseleave替代mouseover/mouseout,这类事件不会冒泡,能减少不必要的触发;绑定到父容器后,只要鼠标在容器内,动画就会持续播放。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:08:16