简体   繁体   中英

Javascript mute/unmute video using image

For some reason, it's just not working.. What am I doing wrong? I want to be able to mute and unmute the video using an image, which is changing whether the video is muted or not.

  function mute() { var video = document.getElementById("bgvid"); if (!video.muted) { document.getElementById('muteicon').src = "Images/muteicon.png"; video.muted; } else { document.getElementById('muteicon').src = "Images/soundicon.png"; video.muted == false; } } 
 video#bgvid { margin-top: 30px; margin-bottom: 60px; width: 1280px; height: 720px; background-size: cover; } video { display: block; } 
 <video autoplay loop id="bgvid"> <source src="newyork.mp4" type="video/mp4"> </video> <br><br> <img alt="mute icon" src="Images/soundicon.png" id="muteicon" onclick="mute()"> <script> </script> 

You have to use the assign( = ) operator instead of the equality( == ) operator:

function mute() {
    var video = document.getElementById("bgvid");

    if (!video.muted) {
        document.getElementById('muteicon').src = "Images/muteicon.png";
        // video.muted <- not assigned to true
        video.muted = true;
    } else {
        document.getElementById('muteicon').src = "Images/soundicon.png";
        // video.muted == false <- wrong use of equality operator
        video.muted = false;
    }
}

And you can't tell the API to set a property to true just by calling it as you made:

video.muted

You have to assign the property to a value:

video.muted = true

You are not setting the muted property to true when you are trying to mute the video.

if (!video.muted) {
    document.getElementById('muteicon').src = "Images/muteicon.png";
    video.muted = true; // you need to assign this value to true
} else { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM