简体   繁体   中英

JavaScript html5 video

I have a sample html5 video with simple html code.

What I need to do is a customized mute button for all the videos, meaning:

  • if the user clicks on the mute/unmute button for one video, all the other videos get muted/unmuted as well

Is there any way of doing this?

without your html code it is pretty vague but in JS you can do it:

here is a link of the documentation im using:

https://www.w3schools.com/tags/av_prop_muted.asp

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_muted

<button onclick="enableMute()" type="button">Mute sound</button>
<button onclick="disableMute()" type="button">Enable sound</button>

<video id="myVideo" width="320" height="176" controls>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script>
var vid = document.getElementById("myVideo");

function enableMute() { 
  vid.muted = true;
} 

function disableMute() { 
  vid.muted = false;
} 
</script> 

So to trigger the action on all your videos you can:

add a class preferably or id on all your video tag

make js know about them

var vid  = document.getElementById("myVideo");
var vid1 = document.getElementById("myVideo1");
var vid2 = document.getElementById("myVideo2");
var vid3 = document.getElementById("myVideo3");
var vid4 = document.getElementById("myVideo4");

add an onClick action on a button that trigger an action here Mute action which will mute or unmute your videos using the mute property of your element, the action would like

function enableMute() { 
  vid.muted  = true;
  vid1.muted = true;
  vid2.muted = true;
  vid3.muted = true;
  vid4.muted = true;
} 

I think you could do it without this much duplication of code if you add the same class to all your element, and looping through all of them in the action you trigger when you click on the button and then change for each of them their property but not sure exactly how to do it

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