[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.')
    }
}
相关推荐
Tajang13 分钟前
推荐一个浏览器代理插件(Tajang Proxy),支持Chrome和Edge
前端·chrome·网络安全·渗透测试·靶场·edge
鹏多多17 分钟前
前端音频兼容解决:音频神器howler.js从基础到进阶完整使用指南
前端·javascript·音视频开发
龙仔CLL1 小时前
使用vue-pdf做本地预览pdf文件,通过垂直滚动条展示全部pdf内容,不展示分页按钮
前端·vue.js·pdf
前端架构师-老李1 小时前
12、electron专题(electron-builder)
前端·javascript·electron
Never_Satisfied1 小时前
在JavaScript / HTML中,所有转义字符(字符实体)
html·转义字符·字符实体
IT_陈寒1 小时前
JavaScript性能飞跃:5个V8引擎优化技巧让你的代码提速300%
前端·人工智能·后端
艾小码1 小时前
这份超全JavaScript函数指南让你从小白变大神
前端·javascript
reembarkation2 小时前
vue 右键菜单的实现
前端·javascript·vue.js
00后程序员张4 小时前
Fiddler抓包工具使用教程,代理设置与调试方法实战解析(含配置技巧)
前端·测试工具·ios·小程序·fiddler·uni-app·webview
gplitems1237 小时前
Consua WordPress Theme — Business Consulting Sites That Convert With Clarity
javascript