简体   繁体   中英

Toggle HTML5 video mute with pure Javascript

I'm trying to toggle mute/unmute on different videos with a custom button, without using jQuery. Here's my code:

const videoContainerCollection = document.getElementsByClassName('video-container'),
videoContainerArray = [...videoContainerCollection];
videoContainerArray.forEach(function(e) {
  const video = e.querySelector('video'),
  button = e.querySelector('button');
  video.muted = true;
  button.addEventListener('click', function() {
    button.classList.toggle('muted');
    if (video.muted = true) {
      video.muted = false;
    }
    else if (video.muted = false) {
      video.muted = true;
    }
  });
});

I am able to unmute each video, but I'm not able to mute it again. What am I doing wrong here?

const videoContainerCollection = document.getElementsByClassName('video-container'),
videoContainerArray = [...videoContainerCollection];
videoContainerArray.forEach(function(e) {
  const video = e.querySelector('video'),
  button = e.querySelector('button');
  video.muted = true;
  button.addEventListener('click', function() {
    button.classList.toggle('muted');
    if (video.muted === true) {
      video.muted = false;
    }
    else if (video.muted === false) {
      video.muted = true;
    }
  });
});

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