[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 分钟前
JavaScript 闭包 × C++ 类比:彻底搞懂闭包
开发语言·javascript·c++
smilejingwei22 分钟前
用 AI 编程生成 ECharts 图表并嵌入报表的实践
前端·人工智能·echarts·bi·报表工具·商业智能
Linux运维技术栈44 分钟前
Cloudflare Argo Smart Routing全球加速:优化跨境回源链路,提升跨区域访问体验
大数据·前端·数据库
恋猫de小郭1 小时前
Android CLI ,谷歌为 Android 开发者专研的 AI Agent,提速三倍
android·前端·flutter
Hello--_--World1 小时前
Js 隐式类型转换、JavaScript `==` vs `===` 深度对比表
开发语言·javascript·ecmascript
freewlt1 小时前
从 0 搭建现代前端组件库:2026年完整实战指南
前端
凌冰_1 小时前
Thymeleaf 核心语法详解
java·前端·javascript
AIBox3651 小时前
claude 镜像 api 使用指南(2026 年4 月更新)
java·服务器·前端·人工智能·gpt·前端框架
SuperEugene2 小时前
Vue3 配置文件管理:按模块拆分配置,提升配置可维护性|配置驱动开发实战篇
前端·javascript·vue.js·驱动开发
阿凤212 小时前
后端返回文件二进制流
开发语言·前端·javascript·uniapp