简体   繁体   English

单击视频时,如何使用Javascript切换多个视频的播放/暂停?

[英]How do I use Javascript to toggle play/pause for multiple videos when I click on the video?

When I add onclick="playPause()" to just one video it works great. 当我仅将onclick =“ playPause()”添加到一部视频中时,效果很好。 I click the video and it'll play or pause just like I want it to. 我单击视频,它会按照我想要的方式播放或暂停。 If I have more than one video, even if the videos have different IDs (for example: video id="v1" and video id="v2") whenever I click on one video it'll always play one specific video. 如果我有多个视频,则即使我单击一个视频,即使这些视频具有不同的ID(例如:video id =“ v1”和video id =“ v2”),它也始终会播放一个特定的视频。 Using this script on multiple videos seems to only allow play/pause toggling on one video. 在多个视频上使用此脚本似乎仅允许在一个视频上播放/暂停切换。 Here's the html and script I'm using: 这是我正在使用的html和脚本:

<video id="v1" width="480px" height="267px" controls onclick="playPause()">
<source src="S12E13%203%20Acts%20of%20God.mp4" type="video/mp4">
</video>
    <script> 
var myVideo = document.getElementById("v1"); 
function playPause() { 
if (myVideo.paused) 
    myVideo.play(); 
else 
    myVideo.pause(); } 
    </script>


<video id="v2" width="480px" height="267px" controls onclick="playPause()">
<source src="S12E13%203%20Acts%20of%20God.mp4" type="video/mp4">
</video>
    <script> 
var myVideo = document.getElementById("v2"); 
function playPause() { 
if (myVideo.paused) 
    myVideo.play(); 
else 
    myVideo.pause(); } 
    </script>


<video id="v3" width="480px" height="267px" controls onclick="playPause()">
<source src="S12E13%203%20Acts%20of%20God.mp4" type="video/mp4">
</video>
    <script> 
var myVideo = document.getElementById("v3"); 
function playPause() { 
if (myVideo.paused) 
    myVideo.play(); 
else 
    myVideo.pause(); } 
    </script>

Any help would be appreciated! 任何帮助,将不胜感激! BTW: not a big deal, but I've noticed the original Play button doesn't work anymore when I use this script. 顺便说一句:没什么大不了的,但是当我使用此脚本时,我注意到原来的“播放”按钮不再起作用。 Is there a way to fix that? 有办法解决吗? Thanks. 谢谢。

You can use document.getElementsByTagName() or document.querySelectorAll() to find all videos and iterate over them using a single for loop: 您可以使用document.getElementsByTagName()document.querySelectorAll()查找所有视频,并使用单个for循环对其进行迭代:

function playPause() {
 var videos = document.querySelectorAll("video");
 for(var i=0;len=videos.length;i<len i++){
  var myVideo = videos[i];
  if (myVideo.paused) 
    myVideo.play(); 
  else 
    myVideo.pause();
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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