当元素在视口中可见时,自动播放html视频

Automatically play html video when in element becomes visible in viewport

本文关键字:自动播放 html 视频 元素 视口      更新时间:2023-12-28

实际上,我只是想把它作为一种Wiki,在我对它动手动脚之后。

  1. 如何在视口中自动启动视频
  2. 最重要的是:Wordpress兼容解决方案PURE JavaScript。没有JQuery。为什么?因为像我这样的新手很难在wordpress中"查询"图书馆。。。即使只是接收滚动事件也很困难

无论如何,在下面发布答案:

因此,一个直接、最短的解决方案是在html页面上创建视频,或者在WordPress中使用"原始html"元素:

<script type="text/javascript">
  var video = null;
  var ended = false;
  function checkScroll()
  {
    if( video == null )
      return;
    var rect = video.getBoundingClientRect();
    // console.log( rect.top, rect.bottom, window.innerHeight, document.documentElement.clientHeight );
    var inViewPort = Math.abs( rect.top ) < window.innerHeight;
    if( inViewPort )
    {
      if( video.paused && ( ended == false ) )
      {
        video.play();
        video.addEventListener( 'ended', myHandler, false );
        function myHandler(e)
        {
          ended = true;
        }
      }
    }
    else
    {
      video.currentTime = 0;
      ended = false;
    }
  }
  window.onload = function()
  {
    video = document.getElementById( 'rubi-second-video' );
    window.onscroll = function()
    {
      checkScroll();
    }
  }
  checkScroll();