Youtube 视频播放 &暂停取决于使用 jquery 的框架的可见性 [英] Youtube video play & pause depend on visibility of the frame with jquery

查看:18
本文介绍了Youtube 视频播放 &暂停取决于使用 jquery 的框架的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我要感谢 Kosmos 出色的 答案.

如何控制youtube视频播放&暂停取决于帧或播放器的可见性.有什么办法可以用带有 HTML 标签的 youtube 嵌入视频来做到这一点?

例如:




<div class="容器"><ul class="tabs"><li class="tab-link current" data-tab="tab-1">标签一</li><li class="tab-link" data-tab="tab-2">标签二</li><li class="tab-link" data-tab="tab-3">标签三</li><li class="tab-link" data-tab="tab-4">标签四</li><div id="tab-1" class="tab-content current">Lorem ipsum dolor sat amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut Labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exeritation ullamco Laboris nisi ut aliquip ex ea commodo consequat.

<div id="tab-2" class="tab-content">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.例外 sint occaecat cupidatat non proident, 在 culpa qui offcia deserunt mollit anim id est labourum 中被禁止.

<div id="tab-3" class="tab-content">Ut enim ad minim veniam, quis nostrud exeritation ullamco Laboris nisi ut aliquip ex ea commodo consequat.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

<div id="tab-4" class="tab-content"><iframe id="playerA" width="300" height="220" src="https://www.youtube.com/embed/0_P4pKbvaII?rel=0" frameborder="0" allowfullscreen></iframe>

</div><!-- 容器 -->

如果上述框架可见视频自动播放,并且框架隐藏或向下滚动,如DEMO jsfiddle 会自动暂停.

JS 来自Kosmos的答案,即适用于滚动方法(感谢他),这意味着如果用户滚动视频暂停,如果再次滚动到视口中的视频帧,它将开始播放.不,我的问题是如何使用 HTML 标签实现这一点

var LoadVideo = function(player_id){var 程序 = {初始化:函数(){this.NewPlayer();this.EventHandler();},新播放器:函数(){var _this = this;this.Player = new YT.Player(player_id, {});_this.Player.$element = $('#' + player_id);},播放:函数(){if( this.Player.getPlayerState() === 1 ) 返回;this.Player.playVideo();},暂停:函数(){if( this.Player.getPlayerState() === 2 ) 返回;this.Player.pauseVideo();},滚动控件:函数(){if(Utils.IsElementInViewport(this.Player.$element[0])) this.Play();否则 this.Pause();},事件处理程序:函数(){var _this = this;$(window).on('scroll', function(){_this.ScrollControl();});}};var Utils = {/** @author https://stackoverflow.com/a/7557433/1684970 */IsElementInViewport:函数(el){if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];var rect = el.getBoundingClientRect();返回 (rect.top >= 0 &&rect.left >= 0 &&rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&rect.right <= (window.innerWidth || document.documentElement.clientWidth));}};Program.Init();};window.onload = 函数(){LoadVideo('playerA');LoadVideo('playerB');LoadVideo('playerC');//或(循环模式)//$('iframe').each(function(){//LoadVideo($(this).attr('id'));//});};

请帮助或分享您的想法将不胜感激.谢谢!

解决方案

好吧,我做了一个简单的例子来使用 Youtube Iframe API 来做你正在寻找的事情.

这里是 jsfiddle:https://jsfiddle.net/kmsdev/gsfkL6xL/

这是代码(请参阅 API 文档以更好地理解它):

<块引用>

示例代码已更新以匹配 OP 请求.我刚刚添加了一个事件侦听 tab 点击事件的处理程序.不要忘记追加&enablejsapi=1 到 iframe 源 url,否则 API 将无法工作.由于现在的想法不仅仅是播放和停止视频通过滚动,也许这段代码不是最好的选择,但它仍然是一个解决方法.

更新 jsFiddle:https://jsfiddle.net/kmsdev/gsfkL6xL/3/

var LoadVideo = function(player_id){var 程序 = {初始化:函数(){this.NewPlayer();this.EventHandler();},新播放器:函数(){var _this = this;this.Player = new YT.Player(player_id, {});_this.Player.$element = $('#' + player_id);},播放:函数(){console.log(this.Player.IsReady);if( this.Player.getPlayerState() === 1 ) 返回;this.Player.playVideo();},暂停:函数(){if( this.Player.getPlayerState() === 2 ) 返回;this.Player.pauseVideo();},滚动控件:函数(){if(Utils.IsElementInViewport(this.Player.$element[0])) this.Play();否则 this.Pause();},事件处理程序:函数(){var _this = this;$(window).on('scroll', function(){_this.ScrollControl();});$('.tab-link').on('click', function(){var $target = $('#' + $(this).data().tab);if( !!$('iframe', $target).length && $('iframe', $target).attr('id') == _this.Player.$element.attr('id')){_this.Play();}});}};var Utils = {/** @author http://stackoverflow.com/a/7557433/1684970 */IsElementInViewport:函数(el){if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];var rect = el.getBoundingClientRect();返回 (rect.top >= 0 &&rect.left >= 0 &&rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&rect.right <= (window.innerWidth || document.documentElement.clientWidth));}};Program.Init();};window.onload = 函数(){LoadVideo('playerA');LoadVideo('playerB');};

随意使用和修改它以达到您的目的.

First I want to say thanks to Kosmos for his amazing answer.

How to control youtube video play & pause depend on visibility of the frame or player. Is there any way to do this with youtube embed videos with HTML Tabs?

For example :

<br><br><br>

<div class="container">

    <ul class="tabs">
        <li class="tab-link current" data-tab="tab-1">Tab One</li>
        <li class="tab-link" data-tab="tab-2">Tab Two</li>
        <li class="tab-link" data-tab="tab-3">Tab Three</li>
        <li class="tab-link" data-tab="tab-4">Tab Four</li>
    </ul>

    <div id="tab-1" class="tab-content current">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </div>
    <div id="tab-2" class="tab-content">
         Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    <div id="tab-3" class="tab-content">
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
    </div>
    <div id="tab-4" class="tab-content">
<iframe id="playerA" width="300" height="220" src="https://www.youtube.com/embed/0_P4pKbvaII?rel=0" frameborder="0" allowfullscreen></iframe>
    </div>

</div><!-- container -->

If the above frame visible the video autoplay and if the frame hide or scroll down like DEMO jsfiddle it will auto pause.

JS Answer from Kosmos which is works great with scroll method (thanks to him) that mean if user scroll away the video pause and if again scroll to video frame in viewport it start playing. No My Question is how can implement this with HTML tabs

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

        /** @author https://stackoverflow.com/a/7557433/1684970 */
        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)
            );
        }

    };

    Program.Init();
};

window.onload = function(){
    LoadVideo('playerA');
    LoadVideo('playerB');
    LoadVideo('playerC');

    // or (loop mode)

    //$('iframe').each(function(){
    //  LoadVideo($(this).attr('id'));
    //});
};

Please help or share your idea will be highly appreciate. Thanks!

解决方案

Well, I made a simple example to do what you are looking for using the Youtube Iframe API.

Here's the jsfiddle: https://jsfiddle.net/kmsdev/gsfkL6xL/

And here's the code (see the API docs to understand it better):

Edit:

Example code updated to match OP requests. I just added an event handler to listen to tab click events. Don't forget to append &enablejsapi=1 to the iframe source url, else the API won't work. Since the idea now is a little more than just play and stop the videos by scroll, maybe this code is not the best option, but it is still a workaround.

Updated jsFiddle: https://jsfiddle.net/kmsdev/gsfkL6xL/3/

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(){
            console.log(this.Player.IsReady);
            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();
            });

            $('.tab-link').on('click', function(){
                var $target = $('#' + $(this).data().tab);
                if( !!$('iframe', $target).length && $('iframe', $target).attr('id') == _this.Player.$element.attr('id') ){
                    _this.Play();
                }
            });

        }

    };

    var Utils = {

        /** @author http://stackoverflow.com/a/7557433/1684970 */
        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)
            );
        }

    };

    Program.Init();

};

window.onload = function(){
    LoadVideo('playerA');
    LoadVideo('playerB');
};

Feel free to use and modify it for your purpose.

这篇关于Youtube 视频播放 &amp;暂停取决于使用 jquery 的框架的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆