let muteBtn = document.querySelector('#mute');
muteBtn.addEventListener('click',muteVideo);
function muteVideo(){
if (this.getAttribute('src') == "mute.png") {
video.muted() == false;
this.setAttribute('src', 'mute.png');
} else {
video.muted() == true;
this.setAttribute('src', 'mute.png');
}
}
用于屏蔽视频的Javascript代码。无法使其工作
答案 0 :(得分:0)
您有两个问题:
.muted
是属性,而不是方法。之后不应有()
属性名称。=
分配一个值,而不是==
。==========
video.muted = false;
video.muted = true;
请参见docs。
现在,顺便说一句,如果您通过元素id
获取元素,则最快的DOM查询是.getElementById()
,而不是querySelector()
。另外,您可以通过访问DOM对象的对象属性而不是其HTML属性来更改DOM对象的当前状态。因此,最终的代码是:
let muteBtn = document.getElementById('mute');
muteBtn.addEventListener('click',muteVideo);
function muteVideo(){
if (this.src == "mute.png") {
video.muted = false;
this.src = 'unmute.png';
} else {
video.muted = true;
this.src = 'mute.png;
}
}
说了这么多,将muted
设置为当前值的相反,然后根据当前的muted
值设置图像会更简单:
document.getElementById('mute').addEventListener('click', function(){
video.muted = !video.muted; // Switch mute to the opposite of what it is
// Use a ternary "if" condition to set the image one way or the other:
this.src = (video.muted) ? "mute.jpg" : "unmute.jpg";
}