[Vue3 + TS + Vite] 将带有HTML样式的文本复制到剪切板

换行分割:硬回车

typescript 复制代码
const copyToClipboardWithStyles = async (html: string) => {
    const modifiedHtml = html.replace(/\n/g, '<br>').replace(/ /g, '&nbsp;')
    const item = new ClipboardItem({
        'text/html': new Blob([modifiedHtml], { type: 'text/html' }),
        'text/plain': new Blob([html], { type: 'text/plain' }),
    })
    if (navigator.clipboard) {
        try {
            await navigator.clipboard.write([item])
        } catch (error) {
            console.error('Failed to copy to clipboard:', error)
        }
    } else {
        console.warn('Your browser does not support writing to the clipboard.')
    }
}

换行分割:段落

typescript 复制代码
const copyToClipboardWithStyles = async (html: string) => {
    const paragraphs = html.split('\n').map(line => `<p>${line.replace(/ /g, '&nbsp;')}</p>`)
    const modifiedHtml = paragraphs.join('')
    const item = new ClipboardItem({
        'text/html': new Blob([modifiedHtml], { type: 'text/html' }),
        'text/plain': new Blob([html], { type: 'text/plain' }),
    })
    if (navigator.clipboard) {
        try {
            await navigator.clipboard.write([item])
        } catch (error) {
            console.error('Failed to copy to clipboard:', error)
        }
    } else {
        console.warn('Your browser does not support writing to the clipboard.')
    }
}
相关推荐
英俊潇洒美少年4 分钟前
前端模块化 AMD、CMD、CommonJS、ESM的差异对比
前端
攀登的牵牛花7 分钟前
Claude Code 泄露事件复盘:前端发布流程哪里最容易翻车
前端·github·claude
D_C_tyu15 分钟前
vue3 + vue3-print-nb 插件实现打印功能
前端·javascript·vue.js
paul_chen2115 分钟前
Vite + Vue SPA 在子路径部署(内外网访问+Nginx 反向代理)
前端·vue.js·nginx
星如雨グッ!(๑•̀ㅂ•́)و✧17 分钟前
Reactor背压
java·服务器·前端
笑笑先生24 分钟前
从接口搬运工到研发控制平面,BFF 到底在解决什么?
前端·架构·node.js
霪霖笙箫25 分钟前
「JS全栈AI Agent学习」二、反思、工具使用、规划——让 Agent 从"执行者"变成"自主完成者"
前端·agent·ai编程
前端缘梦26 分钟前
Next.js全栈项目部署全流程|从0到1解决数据库、WebSocket、图片上传所有坑
前端·全栈·next.js
www_stdio27 分钟前
🚀 从 Event Loop 到 AI Agent:我的 Node.js 全栈进阶之路
前端·node.js·nestjs
www_stdio28 分钟前
拒绝做Git“蜘蛛网”制造者!从分支管理到Rebase,带你走一遍标准开发流
前端·github