我正在尝试为音频创建一个切换开关,以取代依赖于状态的图标。这是我的代码(不起作用):
<div id="bgAudioControls">
<a href="#" onclick="muteSound()">
<img id="mute" src="img/sound-off.svg" width="64" height="64" alt="Sound Off" />
</a>
<audio id="bgAudio" autoplay loop preload src="ogg/epic-lead.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</div>
<script language="javascript">
function muteSound() {
if (document.getElementById("mute").src == "img/sound-off.svg")
{
document.getElementById("unmute").src = "img/sound-on.svg";
document.getElementById('bgAudio').muted = true;
}
else
{
document.getElementById("mute").src = "img/sound-off.svg";
document.getElementById('bgAudio').muted = false;
}
}
</script>
我很肯定我忽略了一些超级简单的事情......任何帮助都会受到赞赏。
查看整个代码的实时视图以下代码有效 - 尽管是两个按钮,而不是切换。
<a href="#" onclick="document.getElementById('bgAudio').muted = true;">Mute</a>
<a href="#" onclick="document.getElementById('bgAudio').muted = false;">Unmute</a>
答案 0 :(得分:1)
访问静音元素的“.src”是不正确的,因为src是静音元素的子元素。将id =“mute”直接分配给元素以进行快速修复。
答案 1 :(得分:1)
更新:工作FIDDLE
@Stasik的内容是:
您必须从id="mute"
代码中删除<a>
并将其放入<img>
代码
像这样:
<a href="#" onclick="muteSound()"><img id="mute" src="img/sound-off.svg" /></a>
<强>更新强>
播放/暂停尝试找到here
完整代码
HTML
<div id="bgAudioControls">
<a href="#" >
<img id="mute" src="img/sound-off.svg" width="64" height="64" alt="Sound Off" />
</a>
<audio id="bgAudio" autoplay loop preload src="ogg/epic-lead.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
</div>
JAVASCRIPT
$(function() {
$("#mute").click(function(e) {
e.preventDefault();
var song = $('audio')[0]
if (song.paused){
song.play();
document.getElementById("mute").src = "img/sound-on.svg";
}else{
song.pause();
document.getElementById("mute").src = "img/sound-off.svg";
}
});
});