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

如何用jQuery实现按钮点击与按键触发音效及动画效果

鼓组交互功能修复方案

存在的问题

  • 未引入jQuery依赖:代码使用了jQuery语法,但HTML文件中没有引入jQuery库,会导致$未定义的报错,所有逻辑无法运行。
  • 点击事件参数错误:点击事件的事件对象不存在key属性,直接传递event.key为undefined,无法匹配到对应的音效和动画。
  • 事件对象未显式接收:部分浏览器环境下如果回调函数不主动接收event参数,会无法获取事件对象。

修正后的代码

HTML修改

在引入index.js之前先引入jQuery库,示例如下:

<!-- 引入jQuery,替换为你本地的jQuery文件路径即可 -->
<script src="./jquery.min.js"></script>
<script src="index.js" charset="utf-8"></script>

JavaScript完整代码

$("button").on("click", function(event){
  // 点击时取当前按钮的文本内容作为匹配key
  const key = $(this).text().trim();
  makeSound(key);
  buttonAnimation(key);
});

$(document).keydown(function(event) {
  makeSound(event.key);
  buttonAnimation(event.key);
});

function makeSound(key) {
  switch (key) {
    case "w":
      var audio1 = new Audio("sounds/crash.mp3");
      audio1.play();
      break;
    case "a":
      var audio2 = new Audio("sounds/kick-bass.mp3");
      audio2.play();
      break;
    case "s":
      var audio3 = new Audio("sounds/snare.mp3");
      audio3.play();
      break;
    case "d":
      var audio4 = new Audio("sounds/tom-1.mp3");
      audio4.play();
      break;
    case "j":
      var audio5 = new Audio("sounds/tom-2.mp3");
      audio5.play();
      break;
    case "k":
      var audio6 = new Audio("sounds/tom-3.mp3");
      audio6.play();
      break;
    case "l":
      var audio7 = new Audio("sounds/tom-4.mp3");
      audio7.play();
      break;
    default: console.log("未匹配到对应按键:", key)
  }
}

function buttonAnimation(currentKey) {
  var activeButton = document.querySelector("." + currentKey);
  // 增加存在性判断,避免按下未定义按键时报错
  if (activeButton) {
    activeButton.classList.add("pressed");
    setTimeout(function() {
      activeButton.classList.remove("pressed");
    }, 100);
  }
}

额外说明

请确保sounds目录下的所有音效文件路径正确,否则会出现资源加载报错导致音频无法播放。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:57:02