在滚动时(使用JavaScript或jQuery),如何在网页中播放和暂停YouTube视频



我的意思是说加载页面时不应播放视频。当视频播放器出现在窗口屏幕的焦点上时,它应该播放,并且使用滚动功能在屏幕上不可见时应暂停。我不希望在单独的选项卡上播放视频。

        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
            </head> 
            <body>
                <p>
                    This is some text
                </p>

                <div style="margin-top:1000px;margin-bottom:1000px;">
                <iframe width="445" height="245" src="https://www.youtube.com/embed/LA5XtlyVILo?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>
               </div>
                <script type="text/javascript">
                   var videos = document.getElementsByTagName("iframe"), fraction = 0.8;
                    function checkScroll() {
                      for(var i = 0; i < videos.length; i++) {
                        var video = videos[i];
                        var x = 0,
                            y = 0,
                            w = video.width,
                            h = video.height,
                            r, //right
                            b, //bottom 
                            visibleX, visibleY, visible,
                            parent;

                        parent = video;
                        while (parent && parent !== document.body) {
                          x += parent.offsetLeft;
                          y += parent.offsetTop;
                          parent = parent.offsetParent;
                        }
                        r = x + parseInt(w);
                        b = y + parseInt(h);

                        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) {           
                          playVideo();
                        } else if(visible < fraction) {
                          pauseVideo();                  

                        }

                      }
                    };
                    window.addEventListener('scroll', checkScroll, false);
                    window.addEventListener('resize', checkScroll, false);
                    //check at least once so you don't have to wait for scrolling for the video to start
                    window.addEventListener('load', checkScroll, false);
                    checkScroll();
                    function playVideo() {
                      player.playVideo();
                    }
                    function pauseVideo() {
                      player.pauseVideo();
                    }
                </script>
            </body>
        </html>

基于海报反馈

更新

在stackoverflow上搜索以扩展自己的解决方案后,我在另一个stackoverflow问题中找到了您问题的答案。

这是一个基于原始帖子

的小提琴略微修改的小提琴
 /*Credit to original author http://stackoverflow.com/a/7557433/1684970 */
var LoadVideo = function(player_id) {
var Program = {
  Init: function() {
    this.NewPlayer();
    this.EventHandler();
  },
  NewPlayer: function() {
    var _this = this;
    this.Player = new YT.Player(player_id, {});
    _this.Player.$element = $('#' + player_id);
  },
  Play: function() {
    if (this.Player.getPlayerState() === 1) return;
    this.Player.playVideo();
  },
  Pause: function() {
    if (this.Player.getPlayerState() === 2) return;
    this.Player.pauseVideo();
  },
  ScrollControl: function() {
    if (Utils.IsElementInViewport(this.Player.$element[0])) this.Play();
    else this.Pause();
  },
  EventHandler: function() {
    var _this = this;
    $(window).on('scroll', function() {
      _this.ScrollControl();
    });
  }
};
var Utils = {
  IsElementInViewport: function(el) {
    if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }
};
return Program.Init();
};
LoadVideo('playerA');

原始答案

由于您尚未指定视频是否在iframe或其他任何内容中,我会认为它是嵌入式的,并在YouTube选项中提供了用户播放/暂停/打开。

第一部分是检测元素当前是否在视口中,因此可见。然后,如果可见/不可见,请点击事件。

$(window).scroll(function() {
    var top_of_element = $("#element").offset().top;
    var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).height();
    var top_of_screen = $(window).scrollTop();
    if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // The element is visible, trigger play click event
        $("#element").playVideo()
    }
    else {
        // The element is not visible, trigger pause click event
        $("#element").pauseVideo()
    }
});

您可以通过在页面上观看页面上的滚动事件,以

来解雇玩家的暂停事件
$(window).scroll(function() {
    if($(window).scrollTop() > height) { //height is the pixels by which if you scroll the player gets hidden
        player.pauseVideo();  //player is the YouTube player object you created
    }
    else
        player.playVideo(); //the player is visible.
});

正确的代码。

        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                    <script src="//www.youtube.com/player_api"></script>
            </head> 
            <body>
                <p>
                    This is some text
                </p>
                <div style="margin-top:1000px;margin-bottom:1000px;">
               </div>
                <div id="player"></div>
                <script type="text/javascript">
                    src="//www.youtube.com/player_api"
                    var player;
                    function onYouTubeIframeAPIReady() {
                      player = new YT.Player('player', {
                        height: '245',
                        width: '445',
                        videoId: 'FSfz0NxzN80',
                        rel:'0'             
                      });
                    } 
                   var videos = document.getElementsByTagName("iframe"), fraction = 0.8;
                    function checkScroll() {
                      for(var i = 0; i < videos.length; i++) {
                        var video = videos[i];
                        var x = 0,
                            y = 0,
                            w = video.width,
                            h = video.height,
                            r, //right
                            b, //bottom 
                            visibleX, visibleY, visible,
                            parent;
                        parent = video;
                        while (parent && parent !== document.body) {
                          x += parent.offsetLeft;
                          y += parent.offsetTop;
                          parent = parent.offsetParent;
                        }
                        r = x + parseInt(w);
                        b = y + parseInt(h);
                        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) {           
                      player.playVideo();
                        } 
                        else if(visible < fraction) {
                      player.pauseVideo();
                        }
                      }
                    };
                    window.addEventListener('scroll', checkScroll, false);
                    window.addEventListener('resize', checkScroll, false);
                    //check at least once so you don't have to wait for scrolling for the video to start
                    window.addEventListener('load', checkScroll, false);
                    checkScroll();
                </script>
            </body>
        </html>

最新更新