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

跟随教程制作Wave动画失败,寻求技术帮助(附HTML/CSS/JS代码)

鼠标触发波浪动画无反应问题排查与修复

我按照教程操作实现鼠标移动触发波浪动画,但页面无任何反应,相关代码如下:

HTML代码

<div id="wrapper"></div>

CSS代码

body {
  background-color: black;
}

#wrapper {
  height: 100%;
  width:100%;
  position: fixed;
  bottom: 0px;
  overflow: hidden;
  pointer-events: none;
}

.liquid {
  height: max(300px, 30vw);
  width: max(300px, 30vw);
  background-color: rgb(33, 150, 243);
  border-radius: 100%;
  position: absolute;
  left: 50%;
  top: 100%;
  animation: wave 2s ease-in-out infinite;
}

@keyframes wave {
  from, to {
    transform: translate(-50%, 0%);
  }
  
  50% {
    transform: translate(-50%, -20%);
  }
}

JavaScript代码

const wrapper = document.getElementById("wrapper");

function animateBubble(x) {  
  const bubble = document.createElement("div");
  
  bubble.className = "liquid";
  bubble.style.left = `${x}px`;
  
  wrapper.appendChild(liquid);
  
  setTimeout(() => wrapper.removeChild(liquid), 2000);
}

window.onmousemove = e => animateBubble(e.clientX);

问题原因

JavaScript代码存在变量名不一致的错误:创建的元素变量是bubble,但后续添加、移除元素时误用了未定义的liquid,导致代码执行报错,动画无法触发。

修复后的JavaScript代码

const wrapper = document.getElementById("wrapper");

function animateBubble(x) {  
  const bubble = document.createElement("div");
  
  bubble.className = "liquid";
  bubble.style.left = `${x}px`;
  
  wrapper.appendChild(bubble);
  
  setTimeout(() => wrapper.removeChild(bubble), 2000);
}

window.onmousemove = e => animateBubble(e.clientX);

可选优化建议

  • 给body添加margin: 0,消除页面默认边距带来的布局偏移
  • 频繁创建删除元素可能存在性能损耗,新手阶段可先保证功能正常,后续可尝试用元素池复用元素优化性能

内容的提问来源于stack exchange,提问作者n-clue

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:20:32