[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.')
    }
}
相关推荐
踩着两条虫23 分钟前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
Jagger_35 分钟前
项目上线忙碌结束之后,为什么总想找点事做?
前端
GalenZhang8881 小时前
OpenClaw 配置多个飞书账号实战指南
前端·chrome·飞书·openclaw
steven~~~1 小时前
为什么mq报错
javascript
萌新小码农‍2 小时前
python装饰器
开发语言·前端·python
threelab3 小时前
Three.js 初中数学函数可视化 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
爱学习的程序媛3 小时前
浏览器工作原理全景解析
前端·浏览器·web
凉辰3 小时前
解决 H5 键盘遮挡与页面上推
开发语言·javascript·计算机外设
我是若尘4 小时前
用 Git Worktree 同时开多个需求,不用来回 stash
前端
IT_陈寒4 小时前
Vue的v-for为什么不加key也能工作?我差点翻车
前端·人工智能·后端