[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.')
    }
}
相关推荐
泯泷5 分钟前
Vercel AI SDK 6 完整教程系列 - 第一部分:基础入门篇
前端·javascript
lcy_2412 分钟前
10 万条数据滚动不卡?聊聊我写的虚拟列表组件 vue-virtualize
前端
zhanlang021720 分钟前
HTML 零基础入门到企业实战【第七章 7.5】表单验证基础属性:required、maxlength、placeholder
前端·html
涛涛ing29 分钟前
为了快 30 倍,我把构建工具换成了 Rust,结果团队差点连班都加不了
前端
parade岁月1 小时前
SolidJS 2.0 正式发布:异步成为响应式的一部分
前端
lcy_241 小时前
防抖节流、并发控制、指数退避重试——我把它收进了一个库 async-concurrency-kit
前端
程序员大阳1 小时前
副队长Vue3教程(5)--事件绑定 v-on
前端·javascript·vue.js·vue3·事件绑定·v-on
艾莉丝努力练剑1 小时前
【AI大模型接入SDK】C++的SessionManager 线程安全
java·开发语言·前端·c++·人工智能·学习·安全
泯泷2 小时前
Vercel AI SDK 6 完整教程系列 - 第二部分:结构化数据与工具调用
前端·javascript
OpenTiny社区3 小时前
我用Vue 100%复制DeepSeek开源的网页App,代码更少,功能还更多!
前端·vue.js·github