HTML文档类型导致视频自动播放而不滚动到

HTML Doctype Causing Video Autoplay Without Scrolled to

本文关键字:滚动 自动播放 视频 文档 类型 HTML      更新时间:2023-09-26

基本上,当我向下滚动到视频时,我想自动播放HTML5视频。通过引用这个代码,我得到了我想要的结果。

我的问题是,当我使用<!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);
  }
}
<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>

仅扩展条件:

 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);
  }
}
<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>