首页 > 解决方案 > 如何使用 JavaScript 使图像在点击时播放声音?

问题描述

所以我想使用 JS HTLM 和 CSS 创建我的第一个项目,它就像一个鼓网站......当我点击一个图像时它应该发出声音。因此,我所知道的只是通过单击按钮而不是实际图像来使按钮发出声音。如果你知道我应该在这个 YYY 地方放什么?这是我的 JS 文件代码: PS:soundi 是这个图像的类

var soundi = document.querySelectorAll(".soundi").length;
 for (var i = 0; i < soundi ; i++) {
   document.querySelectorAll(".soundi")[i].addEventListener("click", function () {
var clickDe = this.YYYY;
switch (clickDe) {
  case "YYYY" :
  var tom1 = new Audio('sounds/tom-1.mp3');
  tom1.play();
    break;

}
   })
 }

标签: javascriptaddeventlistener

解决方案


您可以为每个图像添加一个 Id,然后像这样注册事件侦听器:

function imageClicked(event) {
    const imgId = event.target.id; // imgId is the name of the instrument => the name of the sound file without the extension
    const soundFile = new Audio(`sounds/${imgId}.mp3`); // this way, you don't have to use a switch statement which can get very long and chaotic
    soundFile.play();
}


document
    .querySelectorAll(".soundi") // querySelectorAll returns all the images so no need to put it in a for loop
    .forEach((img) => img.addEventListener("click", imageClicked));

您显然必须正确选择图像 ID,以便它们与文件名匹配。


推荐阅读