[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.')
    }
}
相关推荐
xuboyok26 分钟前
PHP vs Java:核心差异与选型指南
开发语言·前端·php
D_C_tyu7 分钟前
Vue3 + Vite 项目实现页面离开时取消所有未完成请求
前端·vue.js
榴莲omega13 分钟前
第10天:手写 bind 与 柯里化 | 从疑惑到通透
开发语言·javascript·ecmascript·bind·柯里化
leafyyuki14 分钟前
Pyenv Rehash 失败:锁文件与‘无法覆盖已有文件’问题
前端
Binarydog_Lee16 分钟前
Tauri2 开发入门:应用是如何启动的
前端·rust·tauri
前端付豪26 分钟前
实现聊天参数面板
前端·人工智能·后端
晨枫阳26 分钟前
从零搭建私有 npm 仓库Verdaccio
前端·npm·node.js
千百元27 分钟前
HBuildx打包总是看不到效果
前端
小李的便利店30 分钟前
系统架构设计师-案例分析-Web系统设计
前端·系统架构
AAA阿giao31 分钟前
React 闭包陷阱详解:为什么你的定时器总在“说谎”?
前端·javascript·react.js