[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.')
    }
}
相关推荐
Timer@25 分钟前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫41 分钟前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81631 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan3 小时前
FastAPI -API Router的应用
前端·网络·python
走粥3 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory0014 小时前
layui select重新渲染
前端·layui
weixin199701080164 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化
九皇叔叔5 小时前
003-SpringSecurity-Demo 统一响应类
java·javascript·spring·springsecurity