我跟着HTML5 and Javascript to play videos only when visible - 它在第一个视频上运行得很好,但是我的网站上的第二个视频也暂停了,当第一个视频是第一个视频时播放(当滚动所有视频时)通往顶部的方式)。第二个视频应该只播放,当它滚动到并以0.1的一小部分可见时(就像在第一个视频上那样)。
我的HTML:
<video id="video1" preload="auto" autoplay="autoplay" loop="loop" style="position: absolute; bottom: 0px; right: 0px; z-index: -100; width: 1440px; height: 810px; left: 0px; top: -2px;">
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
bgvideo
</video>
...
<video id="video2" preload="auto" autoplay="autoplay" loop="loop" style="position: absolute; bottom: 0px; right: 0px; z-index: -100; width: 1440px; height: 810px; left: 0px; top: -2px;">
<source src="video2.mp4" type="video/mp4">
<source src="video2.ogg" type="video/ogg">
<source src="video2.webm" type="video/webm">
bgvideo
</video>
这是我的JS:
var videos = document.getElementsByTagName("video"), fraction = 0.1;
function checkScroll() {
for(var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right
b = y + h, //bottom
visibleX, visibleY, visible;
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);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkScroll, true);
window.addEventListener('resize', checkScroll, false);
所以看来,所有视频(因为getElementByTagName)只在滚动到顶部时播放。我想在视频的0.1分之一可见时播放视频。
希望这是有道理的。谢谢:))
答案 0 :(得分:1)
我将分数改为0.8,对我来说效果很好。希望这有帮助
var videos = document.getElementsByTagName("video"),
fraction = 0.8;
function checkScroll() {
for(var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = video.offsetLeft, y = video.offsetTop, w = video.offsetWidth, h = video.offsetHeight, r = x + w, //right
b = y + h, //bottom
visibleX, visibleY, visible;
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);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);