[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.')
    }
}
相关推荐
去伪存真11 分钟前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li1 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写1 小时前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端
TDengine (老段)2 小时前
TDengine IDMP 知识库与知识图谱
大数据·前端·物联网·知识图谱·时序数据库·tdengine·涛思数据
goehou3 小时前
PNG 转 WebP 不一定变小,我量了三类图
前端·性能优化·webp·sharp
夕水4 小时前
一个小小的颜色选择器,差点让我开发出一个组件库来
前端·javascript·typescript
时间的情敌5 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu121385 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
光影少年6 小时前
ts全栈开发
javascript·后端·typescript·node.js·c5全栈
bai2736 小时前
主线程里 foo 和 FOO 是同一个变量,Worker 里就成了两个:Windows 上 process.env 的大小写边界
javascript·后端