我在编写这个代码时遇到了一些麻烦。我完全没有使用JavaScript的经验,所以我遵循了一个教程。我试图创建一个充满按钮的页面,但是每个按钮播放一个不同的音频。现在我做了两个按钮,但它们的声音完全一样。我试着查看堆栈上的其他一些帖子,但是在没有删除我已经应用过的样式的情况下,我很难修复它。
<html>
<head>
<title>
a button
</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, inital-scale=1" />
<style type="text/css">
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
width: 100%;
height: 100vh;
background: black;
display: flex;
jusitfy-content: center;
align-items: center;
}
#button{
width: 200px;
height: 200px;
border-width: 4px;
border-radius: 50%;
font-size: 40px;
font-weight: bold;
color: black;
cursor: pointer;
}
#button2{
width: 200px;
height: 200px;
border-width: 4px;
border-radius: 50%;
font-size: 40px;
font-weight: bold;
color: black;
cursor: pointer;
}
</style>
</head>
<body>
<button id="button" onclick="audio.play();"> click me </button>
<script type="text/javascript">
const audio = new Audio();
audio.src = "audio/yay.mp3";
</script>
<button id="button2" onclick="audio.play();"> click me </button>
<script type="text/javascript">
const audio = new Audio();
audio.src = "audio/waitwhat.mp3";
</script>
</body>
</html>```发布于 2022-08-04 20:52:22
您可以创建一个音频数组,每个音频具有不同的src,并在相应的索引处调用音频函数。另外,您不需要两个“脚本”标记,您可以将整个逻辑写入单个逻辑。
<script type="text/javascript">
// creates an array of audios and assigns the src to each of them
const srcArr = ['audio/waitwhat.mp3', 'audio/yay.mp3'];
const audios = new Array(srcArr.length).fill(new Audio());
audios.forEach((audio, index) => audio.src = srcArr[index]);
</script>
然后根据srcArr中src的索引将相应的音频传递给onclick函数。
<button id="button" onclick="audios[0].play();"> click me </button>
<button id="button" onclick="audios[1].play();"> click me </button>
https://stackoverflow.com/questions/73241052
复制相似问题