Play/pause HTML 5 video using JQuery

2019-01-01 14:50发布

I am trying to control HTML5 videos using JQuery. I have two clips in a tabbed interface, there are six tabs in total, the others just have images. I am trying to make the video clips play when their tab is clicked and then stop when any of the others are clicked.

This must be a simple thing to do but I cant seem to get it to work, the code I am using to play the video is:

$('#playMovie1').click(function(){
  $('#movie1').play();
      });

I have read that the video element needs to be exposed in a function to be able to control it but can't find an example. I am able to make it work using JS:

document.getElementById('movie1').play();

Any advice would be great. Thanks

15条回答
浪荡孟婆
2楼-- · 2019-01-01 15:04

Your solution shows the issue here -- play is not a jQuery function but a function of the DOM element. You therefore need to call it upon the DOM element. You give an example of how to do this with the native DOM functions. The jQuery equivalent -- if you wanted to do this to fit in with an existing jQuery selection -- would be $('#videoId').get(0).play(). (get gets the native DOM element from the jQuery selection.)

查看更多
十年一品温如言
3楼-- · 2019-01-01 15:04

For pausing multiple videos I have found that this works nicely:

$("video").each(function(){
    $(this).get(0).pause();
});

This can be put into a click function which is quite handy.

查看更多
泪湿衣
4楼-- · 2019-01-01 15:06
<video style="min-width: 100%; min-height: 100%; " id="vid" width="auto" height="auto" controls autoplay="true" loop="loop" preload="auto" muted="muted">
<source src="video/sample.mp4" type="video/mp4">
<source src="video/sample.ogg" type="video/ogg">
</video>
<script> 
$(document).ready(function(){
document.getElementById('vid').play(); });
</script> 
查看更多
牵手、夕阳
5楼-- · 2019-01-01 15:07

This is how I managed to make it work:

jQuery( document ).ready(function($) {
    $('.myHTMLvideo').click(function() {
        this.paused ? this.play() : this.pause();
    });
});

All my HTML5 tags have the class 'myHTMLvideo'

查看更多
姐姐魅力值爆表
6楼-- · 2019-01-01 15:07

I also made it work like this:

$(window).scroll(function() {
    if($(window).scrollTop() > 0)
        document.querySelector('#video').pause();
    else
        document.querySelector('#video').play();
});
查看更多
看淡一切
7楼-- · 2019-01-01 15:08

@loneSomeday explained it beautifully , here one solution which might also give you good idea how to achieve play/pause functionality

play/pause of video on click

查看更多
登录 后发表回答