开发者

Pause Multiple HTML5 Videos

开发者 https://www.devze.com 2023-01-16 00:36 出处:网络
I have multiple HTML5 videos in a slider at http://ghostpool.com/wordpress/phideo and when I click on any of the slider buttons the first video is paused using the following onclick function.

I have multiple HTML5 videos in a slider at http://ghostpool.com/wordpress/phideo and when I click on any of the slider buttons the first video is paused using the following onclick function.

<a href="#" onclick="pausePlayer();">LINK</a>


var htmlPlayer = document.getElementsByTagName('video')[0];

function pausePlayer() {
  htmlPlayer.pause();
}

However the second video does not pause when the slider buttons are clicked. I assume the Javascript above does not work with multiple video开发者_JAVA技巧s?

EDIT: Additionally, if clicking on the video element itself I want to toggle a play and pause function. I"m using this code, but it plays and stops all videos at once. I assume I'm not looping it correctly:

function togglePlayer() {

for(var i = 0; i < htmlPlayer.length; i++){

    if ( htmlPlayer[i].paused || htmlPlayer[i].ended ) {    

        if ( htmlPlayer[i].ended ) { htmlPlayer[i].currentTime = 0; }
        htmlPlayer[i].play();

      }  else { 

      htmlPlayer[i].pause();

    }

}
}


This obviously won't work because you are only getting the first element in the array returned by getElementsByTagName. The [0] part accesses the first element in the array. What you would want to do is to iterate through all of them with a loop, like this:

var htmlPlayer = document.getElementsByTagName('video');

function pausePlayer() {
  for(var i = 0; i < htmlPlayer.length; i++){
    htmlPlayer[i].pause();
  }
}

Edit

Regarding your second question - You can try using this instead:

for(var i = 0; i < htmlPlayer.length; i++){
    htmlPlayer[i].onclick = function() {
        if ( this.paused || this.ended ) {    
            if ( this.ended ) { this.currentTime = 0; }
            this.play();
        }  else { 
            this.pause();
        }
    }
}

this in a event handler should refer to the element that called it.

0

精彩评论

暂无评论...
验证码 换一张
取 消