当用户使用video.js专门滚动时播放视频

时间:2014-08-22 04:06:02

标签: javascript video.js

我之前已经问过这个问题的变体,但是没有一个具体涉及如何在video.js上做这个问题

我正在使用video.js播放我的视频。当用户滚动到他们的视图时,我需要播放视频。很多人都问过关于html5的视频,但我想特别了解video.js。我做了以下但没有运气 -

var videos = videojs('movie-id_html5_api');
videojs("movie-id_html5_api").ready(function(){
  var videos = this;
  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) {
            videos.play();

        } else {
            videos.pause();
        }

   }

  }

    });
    window.addEventListener('scroll', checkScroll, false);
    window.addEventListener('resize', checkScroll, false);

我还应该提到我有多个具有相同ID的视频&#39; movie-id_html5_api&#39;我想在滚动时让他们玩。

提前谢谢!!

1 个答案:

答案 0 :(得分:0)

我更新了jsFiddle以仅播放每个视频,如果它已滚动到视图中。如果视频不在视野中,则会暂停播放。相信这个Stack Overflow answer用于playVideos功能,也用于将每个视频播放器ID存储在一个数组中。对于isOnScreen()函数,还可以使用此Stack Overflow answer

videojs.options.flash.swf = "http://vjs.zencdn.net/c/video-js.swf";
var players = ['example_video_1', 'example_video_2'];

window.addEventListener("resize", playVideos, false);
window.addEventListener("scroll", playVideos, false);

// Loop through all the players, check if video player is visible in the viewport. If it is visible, play it. If not, do not play it.
function playVideos() {

    for (var i = 0; i < players.length; i++) 
    {
        var videoPlayer = $('#' + players[i]);
        var videoPlayerElem = _V_('#' + players[i]);

        if (isOnScreen(videoPlayer))
        {
             videoPlayerElem.play();
        }
        else
        {
             videoPlayerElem.pause();
        }     
    }

}

function isOnScreen(element) {
   var elementOffsetTop = element.offset().top;
   var elementHeight = element.height();

   var screenScrollTop = $(window).scrollTop();
   var screenHeight = $(window).height();

   var scrollIsAboveElement = elementOffsetTop + elementHeight - screenScrollTop >= 0;
   var elementIsVisibleOnScreen = screenScrollTop + screenHeight - elementOffsetTop >= 0;

   return scrollIsAboveElement && elementIsVisibleOnScreen;
}