前端实现画中画,让网页飞出浏览器

前端实现画中画,让网页飞出浏览器

在前端开发中,我们常常追求创新的交互方式来提升用户体验。今天,我要和大家分享一个非常酷的功能:文档画中画(Document Picture-in-Picture,简称 PiP)。这个功能可以让你网页上的任何内容悬浮在桌面上,无论用户如何切换页面,它都能始终保持在屏幕的最上层。

一、PiP 的核心实现

PiP 的核心方法是 window.documentPictureInPicture.requestWindow,这是一个异步方法,返回一个新创建的 window 对象。这个对象可以看作是一个新的网页,但它始终悬浮在屏幕上方。

xml 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Picture-in-Picture API 示例</title>
    <style>
        #pipContent {
            width: 600px;
            height: 300px;
            background: pink;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="pipContent">这是一个将要放入画中画的 div 元素!</div>
        <button id="clickBtn">切换画中画</button>
    </div>
    <script>
        // 检查是否支持 PiP 功能
        if ('documentPictureInPicture' in window) {
            console.log("🚀 浏览器支持 PiP 功能!");
        } else {
            console.warn("⚠️ 当前浏览器不支持 PiP 功能,更新浏览器或者换台电脑吧!");
        }

        // 请求 PiP 窗口
        document.getElementById("clickBtn").addEventListener("click", async function () {
            const pipContent = document.getElementById("pipContent");

            // 请求创建一个 PiP 窗口
            const pipWindow = await window.documentPictureInPicture.requestWindow({
                width: 200,  // 设置窗口的宽度
                height: 300  // 设置窗口的高度
            });

            // 将原始元素克隆并添加到 PiP 窗口中
            pipWindow.document.body.appendChild(pipContent.cloneNode(true));

            // 设置 PiP 样式同步
            [...document.styleSheets].forEach((styleSheet) => {
                try {
                    const cssRules = [...styleSheet.cssRules].map((rule) => rule.cssText).join('');
                    const style = document.createElement('style');
                    style.textContent = cssRules;
                    pipWindow.document.head.appendChild(style);
                } catch (e) {
                    const link = document.createElement('link');
                    link.rel = 'stylesheet';
                    link.type = styleSheet.type;
                    link.media = styleSheet.media;
                    link.href = styleSheet.href ?? '';
                    pipWindow.document.head.appendChild(link);
                }
            });

            // 监听进入和退出 PiP 模式的事件
            pipWindow.addEventListener("pagehide", (event) => {
                console.log("已退出 PIP 窗口");
            });

            pipWindow.addEventListener('focus', () => {
                console.log("PiP 窗口进入了焦点状态");
            });

            pipWindow.addEventListener('blur', () => {
                console.log("PiP 窗口失去了焦点");
            });
        });
    </script>
</body>
</html>

二、设置 PiP 样式

为了让 PiP 窗口更加美观,我们需要同步原始页面的样式。可以通过 document.styleSheets 获取所有样式信息,并将其应用到 PiP 窗口中。

ini 复制代码
[...document.styleSheets].forEach((styleSheet) => {
    try {
        const cssRules = [...styleSheet.cssRules].map((rule) => rule.cssText).join('');
        const style = document.createElement('style');
        style.textContent = cssRules;
        pipWindow.document.head.appendChild(style);
    } catch (e) {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = styleSheet.type;
        link.media = styleSheet.media;
        link.href = styleSheet.href ?? '';
        pipWindow.document.head.appendChild(link);
    }
});

三、监听 PiP 事件

我们还可以为 PiP 窗口添加事件监听,监控画中画模式的进入和退出,以及焦点变化。

javascript 复制代码
// 监听退出 PiP 模式的事件
pipWindow.addEventListener("pagehide", (event) => {
    console.log("已退出 PIP 窗口");
});

// 监听焦点和失焦事件
pipWindow.addEventListener('focus', () => {
    console.log("PiP 窗口进入了焦点状态");
});

pipWindow.addEventListener('blur', () => {
    console.log("PiP 窗口失去了焦点");
});

四、完整示例

通过以上步骤,我们已经实现了一个完整的 PiP 功能。点击按钮后,指定的元素将悬浮在屏幕上方,并且可以随用户操作进行相应的反馈。

xml 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Picture-in-Picture API 示例</title>
    <style>
        #pipContent {
            width: 600px;
            height: 300px;
            background: pink;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="pipContent">这是一个将要放入画中画的 div 元素!</div>
        <button id="clickBtn">切换画中画</button>
    </div>

    <script>
        // 检查是否支持 PiP 功能
        if ('documentPictureInPicture' in window) {
            console.log("🚀 浏览器支持 PiP 功能!");
        } else {
            console.warn("⚠️ 当前浏览器不支持 PiP 功能,更新浏览器或者换台电脑吧!");
        }

        // 请求 PiP 窗口
        document.getElementById("clickBtn").addEventListener("click", async function () {
            const pipContent = document.getElementById("pipContent");

            // 请求创建一个 PiP 窗口
            const pipWindow = await window.documentPictureInPicture.requestWindow({
                width: 200,  // 设置窗口的宽度
                height: 300  // 设置窗口的高度
            });

            // 将原始元素克隆并添加到 PiP 窗口中
            pipWindow.document.body.appendChild(pipContent.cloneNode(true));

            // 设置 PiP 样式同步
            [...document.styleSheets].forEach((styleSheet) => {
                try {
                    const cssRules = [...styleSheet.cssRules].map((rule) => rule.cssText).join('');
                    const style = document.createElement('style');
                    style.textContent = cssRules;
                    pipWindow.document.head.appendChild(style);
                } catch (e) {
                    const link = document.createElement('link');
                    link.rel = 'stylesheet';
                    link.type = styleSheet.type;
                    link.media = styleSheet.media;
                    link.href = styleSheet.href ?? '';
                    pipWindow.document.head.appendChild(link);
                }
            });

            // 监听进入和退出 PiP 模式的事件
            pipWindow.addEventListener("pagehide", (event) => {
                console.log("已退出 PIP 窗口");
            });

            pipWindow.addEventListener('focus', () => {
                console.log("PiP 窗口进入了焦点状态");
            });

            pipWindow.addEventListener('blur', () => {
                console.log("PiP 窗口失去了焦点");
            });
        });
    </script>
</body>
</html>

希望这篇文章能帮助你掌握 Document Picture-in-Picture API 的使用,为你的项目带来更灵活的交互体验。

相关推荐
前端大波2 分钟前
使用webpack-bundle-analyzer 对 react 老项目进行打包优化
前端·react.js·webpack·性能优化
前端 贾公子9 分钟前
(catalog协议) == pnpm (5)
前端·javascript·react.js
JarvanMo13 分钟前
深度解析:如何彻底终结 Flutter 异步操作中的 BuildContext 崩溃?
前端
wxr061618 分钟前
部署Spring Boot项目+mysql并允许前端本地访问
前端·spring boot·mysql·持续部署
假装我不帅24 分钟前
jquery-validation使用
前端·javascript·jquery
怕浪猫29 分钟前
React从入门到出门第六章 事件代理机制与原生事件协同
前端·javascript·react.js
天府之绝33 分钟前
uniapp 中使用uview表单验证时,自定义扩展的表单,在改变时无法触发表单验证处理;
开发语言·前端·javascript·vue.js·uni-app
be or not to be34 分钟前
Html-CSS动画
前端·css·html
初恋叫萱萱39 分钟前
技术基石与职场进阶:构建从Web后端到高性能架构的完整知识图谱
前端·架构·知识图谱
木木木一43 分钟前
Rust学习记录--C9 错误处理
前端·学习·rust