jQuery 滚动到时播放 HTML5 视频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15395920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:57:37  来源:igfitidea点击:

Play HTML5 Video when scrolled to

javascriptjqueryhtmlvideohtml5-video

提问by jp89

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?

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

回答by Mikkel Jensen

In brief

简单来说

Let's say our browser window Wcurrently scrolled to y-position scrollTopand scrollBottom

假设我们的浏览器窗口W当前滚动到 y 位置scrollTop并且scrollBottom

Our video will NOT be played when its position is at V1or V2as below snapshot.

我们的视频在其位置位于V1V2低于快照时将不会播放。

enter image description here

在此处输入图片说明

Code details

代码详情

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

回答by RXMESH

hope this helps but it has been answered before

希望这会有所帮助,但之前已经回答过

http://jsfiddle.net/jAsDJ/

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

回答by brianchirls

You can use window.pageXOffsetand window.pageYOffsetto check how far your browser window is scrolled both vertically and horizontally. Use these with window.innerWidthand innerHeightand 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 scrolland resizeevent on the window object to run the check every time the scrolling changes.

您可以使用window.pageXOffsetwindow.pageYOffset来检查浏览器窗口在垂直和水平方向上滚动了多远。使用这些与window.innerWidthinnerHeight和一些基本几何形状的数学计算有多少影片本身的可见页面重叠。将所有这些放在一个函数中,您可以将其附加到window 对象上的scrollresize事件以在每次滚动更改时运行检查。

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

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

回答by HectorGuo

There is a new API for this scenario, called Intersection_Observer_API, which Chrome 51+ and Edge 15+ has supported.

这个场景有一个新的 API,称为Intersection_Observer_API,Chrome 51+ 和 Edge 15+ 已经支持。

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

Here is a simple demo: https://codepen.io/hectorguo/pen/ybOKEJ

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