【发布时间】:2020-12-09 14:34:29
【问题描述】:
如果视频在视口中/不在视口中,我需要播放/暂停视频。
到目前为止有效。问题是,如果用户按下暂停键,视频就会重新开始播放。
// Limitation: Does not work if the element is
// out of view because it is too far right or left
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
setInterval(function() {
$('video').each(function(){
if ($(this).isInViewport()) {
$(this)[0].play();
} else {
$(this)[0].pause();
}
});
}, 1000);
#right {
position: absolute;
top: 2000px;
}
#video1 {
position: absolute;
left: 0px;
top: 1000px;
}
#video2 {
position: absolute;
left: 0px;
top: 2000px;
}
body {
width: 500px;
height: 3000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="info"></div>
<div id="down">
scroll down please...
</div>
<video id="video1" controls muted>
<source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
<source src="https://www.w3schools.com/html/movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<video id="video2" controls muted>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"/>
<source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg"/>
Your browser does not support the video tag.
</video>
我试图观察播放/暂停按钮,以便我可以挂钩事件,但视频标签是一个影子 dom,我不知道如何处理它。
【问题讨论】:
-
在您执行这些操作时 -
$(this)[0].play();和$(this)[0].pause();您还可以设置某种状态(即:用户与视频互动,因此忽略自动播放/暂停)。 -
我认为观察你的脚本是否对视频进行了操作比检查用户是否这样做更容易。我之前的评论有误导性,对不起。在您的代码中的这些点上,您知道交互是自动发生的。
-
@Black 你总是可以在窗口滚动事件上触发函数??如果用户停止滚动,他们可以像往常一样使用播放/暂停按钮,如果他们继续滚动,它将开始或停止视频,无论视频是否可见。
标签: javascript html jquery