javascript - 如何使用 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;
}
})
}
解决方案
您可以为每个图像添加一个 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,以便它们与文件名匹配。
推荐阅读
- c# - Wpf 宽度绑定到带有星号的属性
- java - 带有 replaceFirst 方法的 Java 循环
- python-2.7 - Python 2.7,Tkinter,使点“跟踪”波形
- python - 如何防止python套接字消息在控制台中重叠?
- sql - SQL - 左连接同一张表,使用ON语句匹配左右表时出现问题
- php - 在 Woocommerce 中创建指向外部路由的链接
- git - 如何忽略文件夹以外的某些带有扩展名的文件?
- python - 通过将熊猫中的两列分组来绘制列的直方图
- spring-boot - Spring Boot 集成测试(SpringRunner 错误)
- php - xpath 使用匹配的文本选择 td 前同级