Play HTML5 Video when scrolled to

前端 未结 4 2235
暖寄归人
暖寄归人 2020-12-02 17:14

Is there anyway to autoplay a HTML5 video only when the user has the video (or a certain percentage of the video) in the browser viewport?

4条回答
  •  春和景丽
    2020-12-02 17:59

    You can use window.pageXOffset and window.pageYOffset to check how far your browser window is scrolled both vertically and horizontally. Use these with window.innerWidth and innerHeight and some basic geometry math to calculate how much your visible page overlaps with the video itself. Put this all in a function that you can attach to the scroll and resize event on the window object to run the check every time the scrolling changes.

    Here is some sample code:

    var video = document.getElementById('video'),
        info = document.getElementById('info'),
        fraction = 0.8;
    
    function checkScroll() {
      var x = video.offsetLeft,
          y = video.offsetTop,
          w = video.offsetWidth,
          h = video.offsetHeight,
          r = x + w, //right
          b = y + h, //bottom
          visibleX,
          visibleY,
          visible;
    
      if (window.pageXOffset >= r ||
          window.pageYOffset >= b ||
          window.pageXOffset + window.innerWidth < x ||
          window.pageYOffset + window.innerHeight < y
         ) {    
    
        info.innerHTML = '0%';
        return;
      }
    
      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);
    
      info.innerHTML = Math.round(visible * 100) + '%';
    
      if (visible > fraction) {
        video.play();
      } else {
        video.pause();
      }
    
    }
    
    window.addEventListener('scroll', checkScroll, false);
    window.addEventListener('resize', checkScroll, false);
    
    //one time at the beginning, in case it starts in view
    checkScroll();
    
    //as soon as we know the video dimensions
    video.addEventListener('loadedmetadata', checkScroll, false);
    

    And a working example.

    This code assumes a pretty simple page layout. If your video is positioned absolutely inside another element that has "position: relative" set, then you'll need to do a little more work to calculate the correct position of the video. (The same goes if the video has been moved with CSS transforms.)

提交回复
热议问题