Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

html - play pause html5 video javascript

I have a function that plays a video when I click on the poster image displayed in the player and it seems to work :

var video = document.getElementById('player');
video.addEventListener('click',function(){
    video().play();
},false);

In the html5 video tag i have something like: id="player" onclick="this.play();"

the problem is if I press pause on the video controls it does in fact pause which is good but then if I press what is now the play button on the video controls I can see the button change to pause again for a split second then it goes back to being a play button again. So I press play and it only plays for a few frames and then goes back at being paused. The only way to make it play again is to click on the video viewing area.

How can I make it stop going back to pause when using the control bar play/pause button, and how can I make it pause when I click on the video viewing area?

I have tried the following but it doesn't work :

var video = document.getElementById('player');
video.addEventListener('click',function(){
    if(video.paused){
        video().play();
    }else{
        video.pause();
    }
},false);

The reason I want to have the video play when pressing on the actual viewing area is it is too hard to locate the tiny controlbar play button on Android because it is so small, it would be easier for people to simply press the viewing area to get it going. In Firefox the video player plays when I click on the viewing area as well as pauses, which is exactly what I want to happen and it also does this without any javascript needed. In Android, the video just won't play at all when I press on the viewing area. So I am basically trying to force the Android browser to behave as Firefox does natively.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$('#play-pause-button').click(function () {
   var mediaVideo = $("#media-video").get(0);
   if (mediaVideo.paused) {
       mediaVideo.play();
   } else {
       mediaVideo.pause();
  }
});

I have done this in jQuery, which is simple and fast. To try it, you just need to use the ID of the video tag and your play/pause button.

EDIT: In vanilla JavaScript: a video is not a function, but part of DOM hence use

 video.play(); 

Instead of

video().play() **wrong**

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...