[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.')
    }
}
相关推荐
小小小小宇8 分钟前
Harness Engineering 全解析与应用
前端
牧艺1 小时前
cos-design v3.0:从 15 个 Demo 到 49 个组件的视觉特效库
前端·视觉设计
lichenyang4531 小时前
ASCF 架构升级总览:WebRuntimePage 为什么要变薄
前端
道友可好1 小时前
从今天开始:你的第一个 Harness Engineering 实践
前端·人工智能·后端
Linsk1 小时前
组件 = 模板 + 业务逻辑
java·前端·vue.js
二月龙1 小时前
移动端 H5 页面开发:响应式适配 + 低版本兼容实战指南
前端
小强19882 小时前
HTML5 新表单全解:日期、手机号、颜色选择器
前端
妙码生花2 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(二):目录结构、初始化 GIT、设计并开发配置系统
前端·后端·go
鱼人2 小时前
HTML5 本地存储终极指南
前端
超绝大帅哥2 小时前
React的Fiber是什么? Vue为什么不需要Fiber ?
前端