JavaScript html5 视频

问题描述

我有一个带有简单 html 代码的示例 html5 视频。

我需要做的是为所有视频定制一个静音按钮,意思是:

  • 如果用户点击一个视频的静音/取消静音按钮,所有其他视频也会被静音/取消静音立>

有没有办法做到这一点?

解决方法

没有你的 html 代码,它很模糊,但在 JS 中你可以做到:

这是我使用的文档链接:

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> 

因此,要在您的所有视频上触发操作,您可以:

最好在所有视频标签上添加一个类或 id

让js了解他们

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");

在按钮上添加一个 onClick 操作,在此处触发操作 静音操作将使用您元素的静音属性将您的视频静音或取消静音,操作如下

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

我认为,如果您向所有元素添加相同的类,并在单击按钮时触发的操作中循环遍历所有这些类,然后为每个元素进行更改,则无需如此多的重复代码就可以做到这一点他们的财产,但不确定如何去做