本文介绍了滚动时播放HTML5视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只有当用户在浏览器视口中有视频(或视频的某个百分比)时才会自动播放HTML5视频吗?
解决方案简要
假设我们的浏览器窗口 W
当前滚动到y位置 scrollTop
和 scrollBottom
我们的视频不会在播放时播放它的位置在 V1
或 V2
如下快照。
代码详情
$(document).ready(function(){
//获取媒体 - 禁止自动播放(音频或视频)
var media = $('video')。not( autoplay ='autoplay']);
var tolerancePixel = 40;
函数checkMedia(){
//获取当前浏览器的顶部和底部
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){//在
$(this).get之上的`In Brief`节中查看解释(0).play();
} else {
$(this).get(0).pause();
}
});
//
$(document).on('scroll',checkMedia);
});
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?
解决方案
In brief
Let's say our browser window W
currently scrolled to y-position scrollTop
and scrollBottom
Our video will NOT be played when its position is at V1
or V2
as below snapshot.
Code details
$(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视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
07-30 19:43