[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.')
    }
}
相关推荐
李少兄24 分钟前
JavaScript 运算符完全指南
java·开发语言·javascript
志尊宝27 分钟前
Vue3 零基础每日笔记(010):watchEffect——用到谁就自动听谁的“懒人侦听器“
前端·vue.js·笔记
狗哥哥32 分钟前
从“看对方向”到“做出行动”:投资决策卡
前端
拖孩37 分钟前
一个人 + AI 做的小程序,一个月赚了 36 块
前端·后端·微信小程序
weixin_440730501 小时前
playwright实战-渠道应用操作
开发语言·前端·python
lhldsg1 小时前
从零构建智慧场馆解决方案小程序:开发全流程实战
java·前端·小程序
IMPYLH1 小时前
HTML 的 <rp> 元素
前端·javascript·html
晴天161 小时前
npm install -f(--force)深度解析:作用原理、报错根源与风险避坑指南
前端·npm·node.js
IT_陈寒1 小时前
React的状态更新竟然不是同步的?!坑了我一整天
前端·人工智能·后端
科里 Coralyx1 小时前
CoT Toolformer ReAct:工具调用、推理链与 Agent 的起源
前端·react.js·前端框架