使用youtube api在移动设备上禁用youtube视频播放器

时间:2016-08-24 14:28:29

标签: javascript youtube youtube-api

我正在使用youtube api和这个javascript / html代码:

<div class="screen ${sVideo.options.muted ? 'mute' : '' @ context='styleString'}" id="ytbg-${sVideo.id}" data-autoplay="${sVideo.options.autoplay ? 'true' : 'false'}" data-loop="${sVideo.options.loop ? 'true' : 'false'}" data-muted="${sVideo.options.muted ? 'true' : 'false'}" data-videoid="${sVideo.src}"></div>

var tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/player_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var tv,
    playerDefaults = {autoplay: 0, autohide: 1, modestbranding: 1, rel: 0, showinfo: 0, controls: 0, disablekb: 1, enablejsapi: 0, iv_load_policy: 3, loop: 0};


function onYouTubePlayerAPIReady() {
    $("div[id^=ytbg-]").each(function(index, element){
        if($(element).data("videoid")) {
            var videourl = $(element).data("videoid");
            var muted = $(element).data("muted");
            var autoplay = $(element).data("autoplay");
            var loop = $(element).data("loop");
            var id = $(element).attr('id');
            playerDefaults.autoplay = autoplay ? 1 : 0;
            playerDefaults.loop = loop ? 1 : 0;
            if(!tv) {
                tv = {};
            }
            tv[videourl] = {
                videoObject: {},
                vid: {'videoId': videourl, 'suggestedQuality': 'default'},
                mute: muted
            };
            tv[videourl].videoObject = new YT.Player(id, {events: {'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange}, playerVars: playerDefaults, width: '100%', height: '100%'});
        }
    });
}


function onPlayerReady(event) {
    if(!tv) return;
    var iframe = event.target.getIframe();
    var videourl = $(iframe).data("videoid");
    if(!tv[videourl]) return;
    if(!tv[videourl].videoObject) return;
    tv[videourl].videoObject.loadVideoById({videoId: videourl, suggestedQuality:'default'});
    if(tv[videourl].mute) {
        tv[videourl].videoObject.mute();
    }
}
function onPlayerStateChange(e) {
    var iframe = e.target.getIframe();
    var id = $(iframe).attr('id');
    var videourl = $(iframe).data("videoid");
    if (e.data === 1) {
        $('#' + id).addClass('active');
    } else if (e.data === 0){
        tv[videourl].videoObject.seekTo(tv[videourl].vid.startSeconds);
    }
}

我需要知道如何在分辨率为移动时禁用播放器。有没有办法禁用播放器并再次启用它?

1 个答案:

答案 0 :(得分:0)

您可以使用playerVars (object),此对象的属性标识player parameters,可用于自定义播放器。

var player;

function onYouTubeIframeAPIReady() {
player = new YT.Player('video-placeholder', {
width: 600,
height: 400,
videoId: 'Xa0Q0J5tOP0',
playerVars: {
'autoplay': 0,
'autohide': 1, 
'modestbranding' : 1,
'rel' : 0

},
events: {
onReady: initialize
}
});
}

有关详细信息,请查看此tutorial和相关的SO question