[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.')
    }
}
相关推荐
SY_FC2 分钟前
实现一个父组件引入了子组件,跳转到其他页面,其他页面返回回来重新加载子组件函数
java·前端·javascript
糟糕好吃4 分钟前
我让 AI 操作网页之后,开始不想点按钮了
前端·javascript·后端
陈天伟教授10 分钟前
人工智能应用- 天文学家的助手:08. 星系定位与分类
前端·javascript·数据库·人工智能·机器学习
VaJoy12 分钟前
给到夯!前端工具链新标杆 Vite Plus 初探
前端·vite
颜酱2 小时前
BFS 与并查集实战总结:从基础框架到刷题落地
javascript·后端·算法
小彭努力中2 小时前
191.Vue3 + OpenLayers 实战:可控化版权信息(Attribution)详解与完整示例
前端·javascript·vue.js·#地图开发·#cesium
奇舞精选2 小时前
用去年 github 最火的 n8n 快速实现自动化推送工具
前端·agent
奇舞精选2 小时前
实践:如何为智能体推理引入外部决策步骤
前端·agent
无限大62 小时前
AI实战02:一个万能提示词模板,搞定90%的文案/设计/分析需求
前端·后端
朝阳5813 小时前
控制 Nuxt 页面的渲染模式:客户端 vs 服务端渲染
前端·javascript