如何创建带样式且点击后播放不同音频的多个按钮?
解决按钮播放同一音频的问题
问题根源
你重复声明了全局变量audio,第二个<script>块里的const audio会直接覆盖第一个,导致两个按钮最终都指向最后创建的音频实例(也就是waitwhat.mp3)。另外你写了两套几乎完全一样的按钮样式,完全可以合并优化,方便后续加更多按钮。
修复后的完整代码
<html> <head> <title>Sound Buttons</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style type="text/css"> *{ margin: 0; padding: 0; box-sizing: border-box; } body{ width: 100%; height: 100vh; background: black; display: flex; justify-content: center; /* 修正了你拼写错误的jusitfy */ align-items: center; gap: 20px; /* 给按钮之间加个间距,避免挤在一起 */ } /* 用类选择器统一按钮样式,不用重复写ID样式 */ .sound-btn{ width: 200px; height: 200px; border-width: 4px; border-radius: 50%; font-size: 40px; font-weight: bold; color: black; cursor: pointer; } </style> </head> <body> <!-- 给每个按钮绑定不同的播放参数 --> <button class="sound-btn" onclick="playSound('audio/yay.mp3')">Yay!</button> <button class="sound-btn" onclick="playSound('audio/waitwhat.mp3')">Wait What?</button> <script type="text/javascript"> // 写一个通用播放函数,接收音频路径当参数 function playSound(audioPath) { // 每次点击创建新的音频实例,避免重复播放时的冲突 const audio = new Audio(audioPath); audio.play(); } </script> </body> </html>
关键修改说明
- 样式优化:把重复的
#button、#button2样式改成.sound-btn类选择器,后续加新按钮直接加这个类就行,不用再复制一遍样式代码。 - 避免变量覆盖:用一个通用函数
playSound,每次点击按钮时根据传入的路径创建新的音频实例,彻底解决之前变量被覆盖的问题。 - 细节修正:修复了
justify-content的拼写错误,给按钮加了间距,还修改了按钮文本方便区分功能。
扩展小技巧
如果以后要加更多按钮,直接复制下面的代码改路径和文本就行:
<button class="sound-btn" onclick="playSound('audio/你的音频路径.mp3')">按钮文本</button>
内容的提问来源于stack exchange,提问作者melissa
相关产品推荐
相关产品推荐

