首页 文章

滚动到时播放HTML5视频

提问于
浏览
21

无论如何只有当用户在浏览器视口中拥有视频(或视频的某个百分比)时才能自动播放HTML5视频?

4 回答

  • 1

    希望这有所帮助,但它已经得到了回答

    http://jsfiddle.net/jAsDJ/

    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);
    
  • 25

    您可以使用window.pageXOffsetwindow.pageYOffset来检查浏览器窗口在垂直和水平方向上滚动的距离 . 使用 window.innerWidthinnerHeight 以及一些基本几何数学来计算可见页面与视频本身重叠的程度 . 将此全部放在一个函数中,您可以将其附加到窗口对象上的 scrollresize 事件,以便在每次滚动更改时运行检查 .

    以下是一些示例代码:

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

    还有working example .

    此代码假定页面布局非常简单 . 如果您的视频绝对位于另一个设置了“position:relative”的元素中,那么您需要做更多的工作来计算视频的正确位置 . (如果使用CSS转换移动视频,情况也是如此 . )

  • 16

    简而言之

    假设我们的浏览器窗口 W 当前滚动到y位 scrollTopscrollBottom

    我们的视频在其位置为 V1V2 (如下快照)时将不会播放 .

    enter image description here

    代码详情

    $(document).ready(function() {
                // Get media - with autoplay disabled (audio or video)
                var media = $('video').not("[autoplay='autoplay']");
                var tolerancePixel = 40;
    
                function checkMedia(){
                    // Get current browser top and bottom
                    var scrollTop = $(window).scrollTop() + tolerancePixel;
                    var scrollBottom = $(window).scrollTop() + $(window).height() - tolerancePixel;
    
                    media.each(function(index, el) {
                        var yTopMedia = $(this).offset().top;
                        var yBottomMedia = $(this).height() + yTopMedia;
    
                        if(scrollTop < yBottomMedia && scrollBottom > yTopMedia){ //view explaination in `In brief` section above
                            $(this).get(0).play();
                        } else {
                            $(this).get(0).pause();
                        }
                    });
    
                    //}
                }
                $(document).on('scroll', checkMedia);
            });
    
  • 8

    此方案有一个名为Intersection_Observer_API的新API,Chrome 51和Edge 15支持这种API .

    var options = {
        root: document.querySelector('.scroll-container'),
        rootMargin: '0px',
        threshold: 1.0 // trigger only when element comes into view completely
    };
    var ob = new IntersectionObserver((entries, observer) => {
        entries[0].target.classList.toggle('red');
    }, options);
    
    // observe all targets, when coming into view, change color
    document.querySelectorAll('.target').forEach((item) => {
        ob.observe(item);
    });
    

    这是一个简单的演示:https://codepen.io/hectorguo/pen/ybOKEJ

相关问题