HTML5 Video play once scrolled into view.

十年热恋 提交于 2019-12-12 02:49:59

问题


I've got some fullscreen video backgrounds that I want to play once they're scrolled into view.

The code I'm using for the video running is as follows.

<video id="video_background" preload="false" autoplay="false" loop="loop" volume="0"> <source src="video.webm" type="video/webm"> <source src="video.mp4" type="video/mp4"> Video not supported </video> 

The full-screen side works great, the video plays and I'm very happy with how it all looks but I've got a couple of issues.

  1. Even at the point I'm at, the video isn't taking into account the autoplay="false" attribute. It's instantly playing as soon as the page loads.

  2. Can someone point me in the right direction to play html5 video when the section is scrolled into view? I'm using sections such as the following for each bit.

<div class="container"><video id="video_background" preload="false" autoplay="false" loop="loop" volume="0"> <source src="video.webm" type="video/webm"> <source src="video.mp4" type="video/mp4"> Video not supported </video></div></section>

I can't find anything that will let me start a section when it scrolls into view.

Any ideas?


回答1:


According to w3schools.com the autoplay must be coded just if you want autoplay, and ignore if you don't want autoplay.

To know when some element appears in the viewport yo can use jquery.appear plugin:

$('someselector').on('appear', function(event, $all_appeared_elements) {
  // this element is now inside browser viewport: play video
});
$('someselector').on('disappear', function(event, $all_disappeared_elements) {
  // this element is now outside browser viewpor: Pause/stop video?
});

If you don't want to use this jQuery plugin, in this StackOverflow question the accepted response to know where some element is scrolled into view is:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

   return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}


来源:https://stackoverflow.com/questions/26119420/html5-video-play-once-scrolled-into-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!