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

如何用JavaScript移除HTML的onmouseover属性并修复加载动画重复触发问题

解决方案

1. 移除onmouseover属性的方法

当然可以用JavaScript移除元素的onmouseover属性,常用两种方式:

  • 调用元素的removeAttribute()方法:document.documentElement.removeAttribute('onmouseover')
  • 直接将onmouseover属性设为null:document.documentElement.onmouseover = null

不过更根本的是替换触发逻辑,避免依赖onmouseover导致的重复触发问题。

2. 页面加载时自动触发动画(替代onmouseover)

你之前用onload无效,是因为脚本放在<head>里时,DOM元素还没渲染完成,无法获取到inside和load元素。解决这个问题有两种可靠方式:

方式一:将脚本放在<body>末尾

把<script>标签移到</body>前,确保DOM加载完成后再执行脚本,然后直接调用after()触发动画。

方式二:监听DOMContentLoaded事件

在脚本里监听文档加载完成事件,触发动画,兼容所有场景。

3. 防止动画重复触发

添加一个状态变量,标记动画是否已经执行过,避免重复调用after()导致元素回到初始位置。


修改后的完整代码

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Game</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <barload>
    <load class="load" id="load"></load>
    <inside class="inside" id="inside"></inside>
  </barload>
  <!-- 脚本移到body末尾,确保DOM加载完成 -->
  <script src="script.js"></script>
</body>
</html>

JavaScript

const div3 = document.getElementById("inside");
const div4 = document.getElementById("load");
// 标记动画是否已触发,防止重复执行
let animationTriggered = false;

function after() {
  if (animationTriggered) return;
  animationTriggered = true;
  div3.style.animation = "bar 10s linear forwards";
}

div3.addEventListener("animationend", End);

function End() {
  div4.style.animation = "fall 10s forwards ease-in-out";
  div3.style.animation = "fall 10s forwards ease-in-out";
  // 动画完成后彻底清除可能的鼠标触发逻辑
  document.documentElement.removeAttribute('onmouseover');
}

// 页面加载完成后自动触发动画
after();

CSS(保持原有逻辑不变)

html {
  height: 100%;
  width: 100%;
  background: black;
}

.load {
  position: absolute;
  top: 70%;
  left: 40%;
  width: 20%;
  height: 14px;
  border-radius: 4px;
  border: 1px solid #27282c;
  box-shadow: 0 0 8px 4px #27282c;
  background: grey;
}

.inside {
 position: absolute;
  top: 70%;
  left: 40%;
  width: 0.1%;
  height: 14px;
  border-radius: 4px;
  background: red;
  border: 1px solid #27282c;
}

@keyframes bar {
  0% {width: 0.1%;}
  10% {width: 4%;}
  20% {width: 5%;}
  30% {width: 6%;}
  40% {width: 12%;}
  50% {width: 14%;}
  60% {width: 15%;}
  70% {width: 16%;}
  80% {width: 17%;}
  81% {width: 17%;}
  82% {width: 17%;}
  83% {width: 17.8%;}
  84% {width: 17.9%;}
  85% {width: 19%;}
  86% {width: 19.1%;}
  87% {width: 19.6%;}
  88% {width: 19.8%;}
  90% {width: 19.9%;}
  100% {width: 20%;}
}

@keyframes fall {
  0% {top: 70%}
  20% {transform: rotate(190deg);}
  100% {top: 150%;}
}

关键说明

  • 移除了<html>标签上的onmouseover属性,改用页面加载完成后直接调用after(),彻底避免鼠标移动触发的问题。
  • 添加animationTriggered变量确保动画只执行一次,即使意外调用after()也不会重复触发。
  • 脚本移到<body>末尾,确保能正确获取DOM元素,解决之前onload无效的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:14:56