[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.')
    }
}
相关推荐
yatum_20142 分钟前
CentOS 7 集群 SSH 免密与主机名配置文档
linux·前端·网络
014-code9 分钟前
Vue 生命周期完全指南
前端·javascript·vue.js
冴羽yayujs9 分钟前
资深前端都在用的 9 个调试偏方
前端·javascript·调试
Amumu1213812 分钟前
CSS移动端
前端·css·css3
lichenyang45321 分钟前
组件设计模式与通信
前端·javascript·设计模式
im_AMBER37 分钟前
前端性能优化之首屏提速
前端·学习·性能优化
lxh01131 小时前
计算右侧小于当前元素的个数 题解
javascript·数据结构·算法
天天向上10241 小时前
vue 大屏适配的一种实现思路
前端·javascript·vue.js
SuperEugene1 小时前
Vue/Vite 多环境配置实战:dev、test、prod 差异区分与避坑指南|Vue 工程化篇
前端·javascript·vue.js
结网的兔子1 小时前
前端学习笔记(实战准备篇)——用vite构建一个项目【吐血整理】
前端·学习·elementui·npm·node.js·vue