基本上,当我向下滚动到视频时,我想要自动播放HTML5视频。通过引用this code,我得到了我想要的结果。
我的问题是当我使用<!DOCTYPE html>
声明时视频是自动播放而没有滚动。我需要使用<html>
来解决它。
但是当我删除<!DOCTYPE html>
时,我的其他代码会受到影响。所以我被迫使用<!DOCTYPE html>
:(
有人能建议解决这个问题吗?向下滚动时,使用<!DOCTYPE html>
而不影响自动播放视频。抱歉我的英语不好。
function inViewPort (elem) {
//First get the scroll y position (how far the user scrolled down)
var scrollY = document.body.scrollTop;
//Now get the height of the viewport
var screenH=document.body.clientHeight;
//Also get the y position of the element
var yPos=elem.offsetTop;
//And now calculate the maximal y position for elem when it is still visible
var maxY=scrollY+screenH;
if (yPos>scrollY && yPos<maxY) {
//It is in the users viewport
return true;
} else {
//It isn't in the users viewport
return false;
}
}
function checkStart (videoName) {
var elem = document.getElementById(videoName);
if (inViewPort(elem)) {
elem.load();
elem.play();
} else if (!elem.ended) {
setTimeout("checkStart('"+videoName+"');", 100);
}
}
&#13;
<body onLoad="checkStart('vid');">
<div style="witdh: 100%; height: 1000px; background: #aaaaaa;">
<h1>Scroll down to start the video</h1>
</div>
</p>
<video src="http://www.w3schools.com/tags/movie.mp4" id="vid" width="500px" controls>
Your browser doesn't support this video. Please upgrade your browser.
</video>
</body>
&#13;
答案 0 :(得分:1)
只是扩展条件:
if (yPos > scrollY && yPos < maxY && scrollY !=0 )
当用户滚动到特定视频位置
时,这将有效
function inViewPort (elem) {
//First get the scroll y position (how far the user scrolled down)
var scrollY = document.body.scrollTop;
//Now get the height of the viewport
var screenH=document.body.clientHeight;
//Also get the y position of the element
var yPos=elem.offsetTop;
//And now calculate the maximal y position for elem when it is still visible
var maxY=scrollY+screenH;
if (yPos>scrollY && yPos<maxY && scrollY !=0) {
//It is in the users viewport
return true;
} else {
//It isn't in the users viewport
return false;
}
}
function checkStart (videoName) {
var elem = document.getElementById(videoName);
if (inViewPort(elem)) {
elem.load();
elem.play();
} else if (!elem.ended) {
setTimeout("checkStart('"+videoName+"');", 100);
}
}
&#13;
<body onLoad="checkStart('vid');">
<div style="witdh: 100%; height: 1000px; background: #aaaaaa;">
<h1>Scroll down to start the video</h1>
</div>
</p>
<video src="http://www.w3schools.com/tags/movie.mp4" id="vid" width="500px" controls>
Your browser doesn't support this video. Please upgrade your browser.
</video>
</body>
&#13;