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

基于Javascript和HTML的按键发声鼓组功能失效求助

在线鼓组按键无响应问题修复

你的代码核心问题有两个:

  • 页面中不存在id为KeyZ/KeyX/KeyA/KeyC的元素,所以document.getElementById(e.code).click()这行代码完全无效
  • 定义好的play函数从未被调用,导致音频根本没机会播放

直接修改按键监听逻辑,去掉无效的元素点击操作,直接调用play函数即可解决问题:

<!DOCTYPE html>
<html>
<body>

<h2>Simple Drumkit!</h2>
<p>C = Kick, A = Crash, Z and X = Snare!</p>

<script>
const sounds = {
  'KeyZ': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyX': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/snare1.ogg',
  'KeyA': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/crash1.ogg',
  'KeyC': 'https://www.virtualdrumming.com/drums/virtual-drum-sounds/hip-hop/kik.ogg'
}

const play = sound => {
  console.log("playing",sound)
  var audio = new Audio(sound);
  audio.play();
}

window.addEventListener('keypress', function(e) { 
  console.log(e.code)
  if (sounds[e.code]) {
    console.log("playing sound for",e.code)
    // 直接调用play函数,传入对应的音频地址
    play(sounds[e.code])
  }  
})
</script> 

</body>
</html>

另外补充一个小优化:如果希望重复按键时音效能连续播放(不会被前一次播放阻塞),可以每次播放前重置音频的播放位置:

const play = sound => {
  console.log("playing",sound)
  var audio = new Audio(sound);
  audio.currentTime = 0; // 重置播放位置,确保重复按键能立即播放
  audio.play();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:35:20