我正试图通过点击事件控制mp3。
<!DOCTYPE html>
<html>
<body>
<audio id="demo" autoplay="true" hidden="hidden">
<source src="Lute.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<div onmousedown="WhichButton(event)">
<img src="Birch-Forest.jpg" alt="A birch forest in the fall"
style="width:600px;height:572px">
</div>
<script>
var playing = false;
function WhichButton(event) {
if (event.button == 0) {
document.getElementById('demo').volume-=0.1;
}
else if (event.button == 1 && playing) {
document.getElementById('demo').pause;
}
else if (event.button == 1 && !playing) {
document.getElementById('demo').play;
}
else if (event.button == 2) {
document.getElementById('demo').volume+=0.1;
}
}
</script>
</body>
</html>
此代码加载图像并开始播放音频,但控件不起作用。我真的不知道我在做什么,只是HTML和JavaScript的初学者。
答案 0 :(得分:0)
你的剧本中有一些错误......让我们看看:
playing
变量初始化为 false ,但您的音频播放器已将自动播放设置为true ...因此,为了清晰起见,您的变量应初始化为 true 或重命名为暂停。但这不是错误:)pause
和play
是函数,所以如果你想调用它们,你必须使用括号,如下所示: document.getElementById('demo').pause();
。反之亦然volume
是属性,因此您不需要括号。您的代码有一些更正:
<script>
var playing = true; // Point 1
var audioPlayer = document.getElementById('demo');
function WhichButton(event) {
if (event.button == 0 && audioPlayer.volume > 0) {
audioPlayer.volume-=0.1;
}
else if (event.button == 1 && playing) {
audioPlayer.pause(); // Point 2
playing = false; // Point 3
}
else if (event.button == 1 && !playing) {
audioPlayer.play();
playing = true;
}
else if (event.button == 2 && audioPlayer.volume < 1) {
audioPlayer.volume+=0.1;
}
}
</script>