[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.')
    }
}
相关推荐
古韵1 分钟前
TanStack Query 被高估了?这 5 个场景它真不如 alova
前端
颂love10 分钟前
Vue3基础入门
前端·学习·vue3
风吹夏回11 分钟前
Vue 3 路由使用完全指南
前端·vue.js
创业之路&下一个五年14 分钟前
JS编程范式 \& 面向对象范式
开发语言·前端·javascript
Js_x17 分钟前
HTML实现类星露谷小游戏
css·html·css3
李白你好17 分钟前
DesJsFinder被动JS分析 + 框架识别 + 主动Fuzz + 响应指纹 — 红队API挖掘利器
javascript
ct97817 分钟前
Axios 请求取消
前端·javascript·vue.js
IT_陈寒21 分钟前
Redis客户端连接池不关闭的后果,程序直接崩给我看
前端·人工智能·后端
怕浪猫21 分钟前
Electron 开发实战(九):调试技巧与开发者工具|测试、性能分析、日志追踪全解
前端·javascript·electron
喜欢踢足球的老罗24 分钟前
产品方案:从已有 CRM AI 系统切入 WhatsApp Chrome 插件赛道
前端·人工智能·chrome