有人可以在Safari中为HTML5播放器提供画中画功能吗?

时间:2018-09-30 13:30:23

标签: javascript jquery html5 webkit

有人可以告诉我如何解决画中画问题吗?我为HTML5播放器添加了它,并从Apple网站上获取了代码,但对我而言不起作用。它给我一个错误的说法:

 TypeError: null is not an object (evaluating 'video.webkitSupportsPresentationMode')
(anonymous function)-jquery-3.min.js:2:31697

代码:

        var video = document.getElementById('video');
        var PiP = document.getElementById('picture-in-picture');

        // picture-in-picture

        if (video.webkitSupportsPresentationMode && typeof video.webkitSetPresentationMode === "function") {
          // Toggle PiP when the user clicks the button.
          PiP.addEventListener("click", function(event) {
            video.webkitSetPresentationMode(video.webkitPresentationMode === "picture-in-picture" ? "inline" : "picture-in-picture");
          });
        } else {
          PiP.disabled = true;
        }

我不确定是否要放置此代码。我只是将其放在页脚的javascript脚本标签内。

更新: 我替换了:

var video = document.getElementById('video');
var PiP = document.getElementById('picture-in-picture');

仅:

var video = $( "video" );
var PiP = $( "#picture-in-picture" );

在jQuery内部准备就绪,错误消失了,但仍然无法正常工作。我对 if else 的每个条件都发出了警报,看起来它甚至无法识别该功能。

           if (video.webkitSupportsPresentationMode && typeof video.webkitSetPresentationMode === "function") {
              // Toggle PiP when the user clicks the button.
              PiP.addEventListener("click", function(event) {
                video.webkitSetPresentationMode(video.webkitPresentationMode === "picture-in-picture" ? "inline" : "picture-in-picture");
              });
                alert("works")
            } else {
              PiP.disabled = true;
                alert("no works") //<--- This is the alert I get
            }

到目前为止,我从未尝试过此PiP。是不是Apple在新的Safari中删除了此功能?好像我去的任何html5视频在全屏旁边都已经有此选项。但是对于自定义HTML5播放器来说并不合适,这就是为什么我想将此功能添加到按钮上的原因。

1 个答案:

答案 0 :(得分:0)

为什么会出错?

document.getElementById返回一个DOM对象,而jQuery对象(由$方法创建)是DOM元素或一组DOM的包装。您可以read the detailed explanation here

这意味着如果您想使用jQuery,则需要进行更改:

var video = $( "video" );

var video = $( "video" )[0];

只是提示

webkitSupportsPresentationMode在iPhone和iPod上返回true,这可能是Safari中的错误,但是由于iPhone和iPod不支持PiP,因此建议您将其添加到脚本中

var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|webOS|BlackBerry|IEMobile|Opera Mini)/i)[0];

然后在运行脚本之前检查iPad

if (isMobile == 'iPad') {
    if (video.webkitSupportsPresentationMode && typeof video.webkitSetPresentationMode === "function") {
        // Toggle PiP when the user clicks the button.
        PiP.addEventListener("click", function(event) {
            video.webkitSetPresentationMode(video.webkitPresentationMode === "picture-in-picture" ? "inline" : "picture-in-picture");
        });
        alert("works")
    } else {
        PiP.disabled = true;
        alert("no works") //<--- This is the alert I get
    }
} else {
    PiP.disabled = true;
}

来源 Safari Picture In Picture - custom HTML5 video controller