滚动到时播放 HTML5 视频 [英] Play HTML5 Video when scrolled to
本文介绍了滚动到时播放 HTML5 视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否只有当用户在浏览器视口中有视频(或视频的特定百分比)时才自动播放 HTML5 视频?
Is there anyway to autoplay a HTML5 video only when the user has the video (or a certain percentage of the video) in the browser viewport?
推荐答案
简要
假设我们的浏览器窗口 W
当前滚动到 y 位置 scrollTop
和 scrollBottom
In brief
Let's say our browser window W
currently scrolled to y-position scrollTop
and scrollBottom
当我们的视频位于V1
或V2
时将不会播放,如下图所示.
Our video will NOT be played when its position is at V1
or V2
as below snapshot.
$(document).ready(function() {
// Get media - with autoplay disabled (audio or video)
var media = $('video').not("[autoplay='autoplay']");
var tolerancePixel = 40;
function checkMedia(){
// Get current browser top and bottom
var scrollTop = $(window).scrollTop() + tolerancePixel;
var scrollBottom = $(window).scrollTop() + $(window).height() - tolerancePixel;
media.each(function(index, el) {
var yTopMedia = $(this).offset().top;
var yBottomMedia = $(this).height() + yTopMedia;
if(scrollTop < yBottomMedia && scrollBottom > yTopMedia){ //view explaination in `In brief` section above
$(this).get(0).play();
} else {
$(this).get(0).pause();
}
});
//}
}
$(document).on('scroll', checkMedia);
});
这篇关于滚动到时播放 HTML5 视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文