简体   繁体   中英

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. 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. 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:

<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:

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();
 }
}

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