滚动播放视频有问题吗? [英] Issue with play video once on scroll?
本文介绍了滚动播放视频有问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果滚动到达#user-experience
部分,我将使用以下代码播放视频:
I use the following code to play a video if the section #user-experience
is reached on scroll:
JS:
var player = $('video');
function isInView(elem){
return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
}
$(window).scroll(function() {
if (isInView($('#user-experience'))) {
// console.log('play video');
player.get(0).play();
}
});
HTML:
<video>
<source src="images/browser.webm" type="video/webm">
<source src="images/browser.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
该代码的问题在于,每当用户滚动一点点,它将触发脚本,直到该部分在浏览器视口中不可见为止.如果用户滚动到#user-experience
部分,则该代码仅应触发一次.滚动到另一部分并返回时,该视频不应第二次播放.
The problem with the code is that it will fire the script every time the user scrolls a little bit, until the section is not visible in the browser viewport. The code should only fire once if the user scrolled to the #user-experience
section. When scroll to another section and back, the video should not play for the second time.
我该如何解决?
推荐答案
喜欢吗?
var player = $('video');
var hasReachedUserExperience = false;
function isInView(elem){
return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
}
$(window).scroll(function() {
if (isInView($('#user-experience')) && !hasReachedUserExperience) {
hasReachedUserExperience = true;
player.get(0).play();
}
});
一个简单的布尔标志似乎满足您的行为要求.
A simple boolean flag seems to meet your behavior requirements.
这篇关于滚动播放视频有问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文