[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.')
    }
}
相关推荐
huashengzsj6 分钟前
Shopify个人建站如何搭建独立站:从零开始的完整指南
前端·网络·人工智能
程序猿小泓17 分钟前
从 Claude Code 学 Agent Harness:一个前端工程师的 AI Agent 学习笔记
前端·人工智能·学习
柒和远方1 小时前
从审计日志到可下载证据包:事务型 Outbox、租约 fencing 与保留水位
前端·后端·架构
minglie11 小时前
npm ali-oss库依赖冲突
前端·npm
CryptoPP2 小时前
BSE股票K线数据接入实战:从接口调用到前端图表展示
大数据·前端·网络·人工智能·websocket·网络协议
没落英雄3 小时前
5. 从零开始搭建一个 AI Agent —— 人机协作与中断恢复
前端·人工智能·架构
品尚公益团队4 小时前
C#在asp.net网页开发中的带cookie登录实现
前端·c#·asp.net
多加点辣也没关系5 小时前
JavaScript|第9章:对象 — 基础
开发语言·javascript·ecmascript
没有了遇见5 小时前
AI Agent 是什么?—— 一文理解 LLM、Memory、Skills、Tools、MCP、Workflow,Context
android·前端·程序员
后台开发者Ethan5 小时前
setState组件更新
前端·javascript·react