【问题标题】:How to play and pause a Youtube video in a webpage while scrolling(using javascript or jquery)?滚动时如何在网页中播放和暂停 Youtube 视频(使用 javascript 或 jquery)?
【发布时间】:2017-06-06 03:40:31
【问题描述】:

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

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

【问题讨论】:

标签: javascript jquery html youtube-api


【解决方案1】:

根据海报反馈进行更新

在 stackoverflow 上搜索以扩展我自己的问题解决方案后,I found the answer to your question in another stackoverflow question.

Here's a fiddle slightly modified fiddle based on the original post

 /*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 选项中播放/暂停/打开。

第一部分是检测元素当前是否在视口中,因此可见。 and then the click event if visible/not-visible.

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

【讨论】:

  • 我已经发布了一个新的解决方案
  • 谢谢,我昨天尝试了这段代码,但它不起作用。无论如何,我找到了解决问题的方法。
  • 您应该将其发布在这里作为答案,以便其他人将来可以找到您的解决方案。
  • 是的,我昨天做了。
【解决方案2】:

您可以通过观看页面的滚动事件来触发播放器的暂停事件

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

【讨论】:

  • 我如何计算高度?
  • @VinayakVishwanathGosain 这是另一个问题,您可以在线搜索比您的更有效的解决方案。
【解决方案3】:

此问题的正确代码。

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

【讨论】:

    猜你喜欢
    • 2017-08-28
    • 2013-11-20
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2013-08-16
    • 2018-05-28
    • 2018-04-28
    • 2017-04-04
    相关资源
    最近更新 更多