[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.')
    }
}
相关推荐
几米哥几秒前
Vercel v0.app:重新定义AI驱动的全栈开发新纪元
前端
冰糖雪梨dd2 分钟前
防御XSS与CSRF攻击
前端·安全
托比-马奎尔12 分钟前
ES6变量与解构:let、const与模板字符串全解析
javascript
excel19 分钟前
JavaScript 并发编程实战:用 Atomics 与 SharedArrayBuffer 玩转多线程与视频渲染
前端
不在了情绪43 分钟前
CSS 基础语法 + 弹性盒子
前端·css
水煮白菜王1 小时前
从零搭建 React 工程化项目
前端·javascript·react.js
会飞的鱼先生1 小时前
react的基本使用
前端·react.js·前端框架
chenglin0161 小时前
C#_接口设计:角色与契约的分离
java·前端·c#
mosen8681 小时前
易混淆的CommonJS和ESM(ES Module)及它们区别
javascript·node.js·express
chenglin0161 小时前
ES_多表关联
java·前端·elasticsearch