Picture-in-Picture API - 允许网站创建一个始终位于其他窗口之上的浮动视频窗口
Picture-in-Picture API(画中画 API)允许网站创建一个始终位于其他窗口之上的浮动视频窗口,以便用户在与其他内容站点或设备上的应用程序交互时可以继续使用该媒体。
接口
PictureInPictureWindow
代表浮动视频窗口;包含宽度和高度属性,以及一个 onresize 事件处理程序属性。
方法
画中画 API 向 HTMLVideoElement 和 Document 接口添加了方法,以允许切换浮动视频窗口。
HTMLVideoElement 接口上的方法
HTMLVideoElement.requestPictureInPicture()
请求用户代理将视频进入画中画模式。
Document 接口上的方法
Document.exitPictureInPicture()
请求用户代理将画中画模式中的元素返回到其原始框中。
属性
Picture-in-Picture API 为 HTMLVideoElement、Document 和 ShadowRoot 接口增加了一些属性,这些属性可以用来确定浮动视频窗口模式是否被支持和可用,画中画模式当前是否激活,以及哪个视频是浮动的。
HTMLVideoElement 接口上的属性
HTMLVideoElement.autoPictureInPicture
当用户切换标签和/或应用程序时,autoPictureInPicture 属性将自动为视频元素进入和离开画中画模式。
HTMLVideoElement.disablePictureInPicture
disablePictureInPicture 属性将向用户代理提供提示,使其不向用户建议画中画或自动请求它。
Document 接口上的属性
Document.pictureInPictureEnabled
pictureInPictureEnabled 属性告诉您是否可以使用画中画模式。如果画中画模式因任何原因不可用(例如“画中画” 功能已被禁止,或不支持画中画模式),则它的值为 false。
Document 或 ShadowRoot 属性上的接口
Document.pictureInPictureElement / ShadowRoot.pictureInPictureElement
pictureInPictureElement 属性告诉您当前在浮动窗口(或 shadow DOM)中显示的是哪个 Element。如果这是 null,则文档(或 shadow DOM)当前没有处于画中画模式的节点。
事件
Picture-in-Picture API 定义了三个事件,可用于检测何时切换画中画模式以及何时调整浮动视频窗口的大小。
enterpictureinpicture
当进入画中画模式时发送到 HTMLVideoElement。关联的事件处理程序是 HTMLVideoElement.onenterpictureinpicture
leavepictureinpicture
当离开画中画模式时发送到 HTMLVideoElement。关联的事件处理程序是 HTMLVideoElement.onleavepictureinpicture
resize
当改变大小时发送到 PictureInPictureWindow。关联的事件处理程序是 PictureInPictureWindow.onresize
控制样式
:picture-in-picture CSS 伪类 匹配当前处于画中画模式的视频元素,允许您配置样式表以在视频播放时自动调整内容的大小、样式或布局在画中画和传统演示模式之间来回切换。
控制访问
可以使用功能策略控制画中画模式的可用性。全屏模式功能由字符串 "picture-in-picture" 标识,默认允许列表值为 "self",这意味着画中画模式允许在顶级文档上下文中使用,也允许从与最顶级文档相同的来源加载的嵌套浏览上下文。
请参阅使用功能策略以了解有关使用功能策略控制对 API 的访问的更多信息。
实例
切换画中画模式
当用户单击 “切换画中画” 按钮时,处理程序会调用此代码:
function togglePictureInPicture() {
if (document.pictureInPictureElement) {
document.exitPictureInPicture();
} else {
if (document.pictureInPictureEnabled) {
video.requestPictureInPicture();
}
}
}
该代码段首先查看 document 的 pictureInPictureElement 属性的值。如果该值为 null,则表示浮动窗口中没有视频。所以我们可以请求视频进入画中画模式;否则,它表示当前处于画中画模式的元素。切换到画中画模式是通过在 video 元素上调用 HTMLVideoElement.requestPictureInPicture() 来完成的。
如果视频在浮动窗口中(pictureInPictureElement 不是null),我们在 document 上调用 exitPictureInPicture() 将视频带回它的初始框中。
规范
| 规范 |
|---|
| Picture-in-Picture |
浏览器兼容性
HTMLVideoElement.requestPictureInPicture
桌面浏览器兼容性
暂无兼容数据
HTMLVideoElement.autoPictureInPicture
桌面浏览器兼容性
暂无兼容数据
HTMLVideoElement.disablePictureInPicture
桌面浏览器兼容性
暂无兼容数据
Document.pictureInPictureEnabled
桌面浏览器兼容性
暂无兼容数据
Document.exitPictureInPicture
桌面浏览器兼容性
暂无兼容数据
Document.pictureInPictureElement
桌面浏览器兼容性
暂无兼容数据
PictureInPictureWindow
桌面浏览器兼容性
暂无兼容数据