[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.')
    }
}
相关推荐
A923A14 分钟前
【从零开始学 React | 第四章】useEffect和自定义Hook
前端·react.js·fetch·useeffect
ZC跨境爬虫18 分钟前
批量爬取小说章节并优化排版(附完整可运行脚本)
前端·爬虫·python·自动化
ZC跨境爬虫20 分钟前
海南大学交友平台登录页开发实战day4(解决python传输并读取登录信息的问题)
开发语言·前端·python·flask·html
来一颗砂糖橘23 分钟前
pnpm:现代前端开发的高效包管理器
前端·pnpm
前端摸鱼匠24 分钟前
Vue 3 的defineProps编译器宏:详解<script setup>中defineProps的使用
前端·javascript·vue.js·前端框架·ecmascript
木斯佳25 分钟前
前端八股文面经大全: 美团财务科技前端一面 (2026-04-09)·面经深度解析
前端·实习面经·前端初级
天外天-亮25 分钟前
Vue2.0 + jsmind:开发思维导图
javascript·vue.js·jsmind
LIO28 分钟前
React 零基础入门,一篇搞懂核心用法(适合新手)
前端·react.js
TeamDev42 分钟前
JxBrowser 8.18.2 版本发布啦!
java·前端·跨平台·桌面应用·web ui·jxbrowser·浏览器控件
netkiller-BG7NYT43 分钟前
yoloutils - Openclaw Agent Skill
前端·webpack·node.js