[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.')
    }
}
相关推荐
摸鱼的春哥2 小时前
春哥的Agent通关秘籍13:实现RAG查询
前端·javascript·后端
明月_清风2 小时前
滚动锁定:用户向上翻看历史时,如何阻止 AI 新消息把它“顶”下去?
前端·javascript
明月_清风2 小时前
当高阶函数遇到 AI:如何自动化生成业务层面的逻辑拦截器
前端·javascript·函数式编程
moshuying12 小时前
别让AI焦虑,偷走你本该有的底气
前端·人工智能
GIS之路13 小时前
ArcPy,一个基于 Python 的 GIS 开发库简介
前端
可夫小子14 小时前
OpenClaw基础-为什么会有两个端口
前端
喝拿铁写前端14 小时前
Dify 构建 FE 工作流:前端团队可复用 AI 工作流实战
前端·人工智能
喝咖啡的女孩15 小时前
React 合成事件系统
前端
从文处安15 小时前
「九九八十一难」组合式函数到底有什么用?
前端·vue.js
前端Hardy15 小时前
面试官:JS数组的常用方法有哪些?这篇总结让你面试稳了!
javascript·面试