我发现这个脚本会在元素位于视口中时自动播放视频
$(window).scroll(function() {
$('#youtube-player-container').each(function(){
var imagePos = $(this).offset().top;
var topOfWindow = $(window).scrollTop();
if (imagePos < topOfWindow+600) {
$('#youtube-player-container').tubeplayer("play");
}
});
});
这很有用,但我也想在视频不再显示时再次暂停视频。我需要编辑/添加什么来实现这一目标?
编辑:我知道有一个动作&#39; tubeplayer(&#34;暂停&#34;)可用,我只是不知道如何激活它。
答案 0 :(得分:1)
试试这个并告诉我它是否有效:
//this version uses a class instead of an ID
$(window).scroll(function() {
$('.youtube-player-container').each(function(){
var imagePos = $(this).offset().top;
var topOfWindow = $(window).scrollTop();
if (imagePos < topOfWindow+600) {
$(this).tubeplayer("play");
}else{
$(this).tubeplayer("pause");
}
});
});
或
//use this one if you are using an ID, but double check this because I wrote it in a hurry.
$(window).scroll(function() {
var videoPos = $('#youtube-player-container')offset().top;
var topOfWindow = $(window).scrollTop();
if (videoPos < topOfWindow+600) {
$('#youtube-player-container').tubeplayer("play");
}else{
$('#youtube-player-container').tubeplayer("pause");
}
});
//double check my blocks, I might not have kept them balanced. I was in a hurry.
答案 1 :(得分:1)
一个非常好的函数,用于确定您的元素是否在视口中 Link
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
总计:
$(window).scroll(function(){
$('.youtube-player-container').each(function(){
var $this = $(this);
var el = $this.get(0);
if (isElementInViewport(el)) {
$this.tubeplayer("play");
} else {
$this.tubeplayer("stop");
}
})
})
PS: id 是一个单一的选择器我认为你打算键入&#39; .youtube-player-container&#39;