var video = document.getElementById('video'),
info = document.getElementById('info'),
fraction = 0.8;
function checkScroll() {
var x = video.offsetLeft,
y = video.offsetTop,
w = video.offsetWidth,
h = video.offsetHeight,
r = x + w, //right
b = y + h, //bottom
visibleX,
visibleY,
visible;
if (window.pageXOffset >= r ||
window.pageYOffset >= b ||
window.pageXOffset + window.innerWidth < x ||
window.pageYOffset + window.innerHeight < y
) {
info.innerHTML = '0%';
return;
}
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
info.innerHTML = Math.round(visible * 100) + '%';
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
//one time at the beginning, in case it starts in view
checkScroll();
//as soon as we know the video dimensions
video.addEventListener('loadedmetadata', checkScroll, false);
$(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);
});
var options = {
root: document.querySelector('.scroll-container'),
rootMargin: '0px',
threshold: 1.0 // trigger only when element comes into view completely
};
var ob = new IntersectionObserver((entries, observer) => {
entries[0].target.classList.toggle('red');
}, options);
// observe all targets, when coming into view, change color
document.querySelectorAll('.target').forEach((item) => {
ob.observe(item);
});
4 回答
希望这有所帮助,但它已经得到了回答
http://jsfiddle.net/jAsDJ/
您可以使用window.pageXOffset和window.pageYOffset来检查浏览器窗口在垂直和水平方向上滚动的距离 . 使用
window.innerWidth
和innerHeight
以及一些基本几何数学来计算可见页面与视频本身重叠的程度 . 将此全部放在一个函数中,您可以将其附加到窗口对象上的scroll
和resize
事件,以便在每次滚动更改时运行检查 .以下是一些示例代码:
还有working example .
此代码假定页面布局非常简单 . 如果您的视频绝对位于另一个设置了“position:relative”的元素中,那么您需要做更多的工作来计算视频的正确位置 . (如果使用CSS转换移动视频,情况也是如此 . )
简而言之
假设我们的浏览器窗口
W
当前滚动到y位scrollTop
和scrollBottom
我们的视频在其位置为
V1
或V2
(如下快照)时将不会播放 .代码详情
此方案有一个名为Intersection_Observer_API的新API,Chrome 51和Edge 15支持这种API .
这是一个简单的演示:https://codepen.io/hectorguo/pen/ybOKEJ