HTML5 and Javascript to play videos only when visible

前端 未结 11 659
梦如初夏
梦如初夏 2020-12-02 12:25

I am interested in setting up an HTML page with multiple video clips such that each video clip plays only while visible and then pauses when out of view.

I have fo

11条回答
  •  没有蜡笔的小新
    2020-12-02 13:07

    In case anyone else runs into this question, I was unable to use Saike's solution on my WordPress site because of the way the videos were auto embedded (MediaElement player). However, qwazix's solution worked with some modification. Here is the jQuery code that works with the IsInView plugin. Here are my include scripts (placed at the end of footer.php in my theme folder).

    
    
    
    

    And the jQuery code (modify 400 to your tolerance liking)

      $(function() {
          $(window).scroll(function() {
              $('.wp-video-shortcode').each(function() {
                  var str = $(this).attr('id');
                  var arr = str.split('_');
                  typecheck = arr[0];
                  if ($(this).is(":in-viewport( 400 )") && typecheck == "mep") {
                      mejs.players[$(this).attr('id')].media.play();
                  } else if (typecheck == "mep") {
                      mejs.players[$(this).attr('id')].media.pause();
                  }
              });
          });
      });
    

    Only issue I have with this code is that it does restart a video clip on scroll even if paused by the user. Wasn't a deal-breaking issue on my site. Here is the code in action: Ultrasoundoftheweek.com

提交回复
热议问题