[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.')
    }
}
相关推荐
小江的记录本3 分钟前
【Swagger】Swagger系统性知识体系全方位结构化总结
java·前端·后端·python·mysql·spring·docker
csdn_aspnet5 分钟前
如何在 .NET Core WebAPI 和 Javascript 应用程序中安全地发送/接收密钥参数
javascript·.netcore·cryptojs
Moshow郑锴10 分钟前
npm国内镜像加速之使用 nrm 工具(灵活切换,适合多环境)
前端·npm·node.js
flytam12 分钟前
Claude Agent SDK 深度入门指南 审核中
前端·人工智能·aigc
还是大剑师兰特13 分钟前
pnpm format 什么作用
开发语言·javascript·ecmascript
你猜猜吧13 分钟前
里程三:DSL总结
前端
JarvanMo13 分钟前
当 Flutter 撞上 3D 性能之墙 —— Fluorite(萤石)
前端
Eagle_Clark13 分钟前
从0到1 Vibe Coding 一个项目的真实感受
前端·人工智能·后端
CodeSheep14 分钟前
兄弟被降职降薪,被猎头挖新公司时承诺45万年薪,结果签合同才发现这45万里有“部分”是股权激励,还得2年后才能兑现
前端·后端·程序员
weixin1997010801621 分钟前
《界面网商品详情页前端性能优化实战》
前端·性能优化