请不要杀了我,因为我确定之前有人问过这个问题,但是当我环顾四周时,没有什么对我有意义。
基本上,当用户向下滚动查看时,我尝试使用以下代码在我的网站上自动播放视频 - http://jsfiddle.net/pjoxqf80/1/
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);
然而,在我的网页上,video.js播放器似乎将视频制作成绝对的&#39;定位使得所有视频仅在用户在页面顶部滚动时播放,然后在用户向下滚动以查看它们时暂停。我希望代码能够正确检测视频的位置。
我想删除绝对的&#39;假设但我使用CDN版本的video.js CSS文件,所以我无法改变它。我想我已经阅读了关于jquery .offset但不确定如何使用它?
以下是该网站,向下滚动以查找视频:
http://www.digital-soul.com.au/tcsite/our-journal-is-different/
答案 0 :(得分:0)
经过大量的搜索,我终于找到了答案 -
How to pause html5 video when out of view code (non-statically positioned)
代码应该像这样工作才能正确检测视频 -
var videos = document.getElementsByTagName("video"),
fraction = 0.8;
function checkScroll() {
for(var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = 0,
y = 0,
w = video.offsetWidth,
h = video.offsetHeight,
r, //right
b, //bottom
visibleX, visibleY, visible,
parent;
parent = video;
while (parent && parent !== document.body) {
x += parent.offsetLeft;
y += parent.offsetTop;
parent = parent.offsetParent;
}
r = x + w;
b = y + h;
//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);