[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.')
    }
}
相关推荐
kisloy1 分钟前
【反爬虫】极验4 W参数逆向分析
java·javascript·爬虫
XPoet5 分钟前
AI 编程工程化:MCP——给你的 AI 员工打通外部能力
前端·后端·ai编程
夏雪之晶莹15 分钟前
JSON语法结构
javascript
笨笨狗吞噬者21 分钟前
小程序包体积分析利器 -- vite-plugin-component-insight
前端·微信小程序·uni-app
吴声子夜歌22 分钟前
Vue3——v-for指令
前端·javascript·vue
你的牧游哥26 分钟前
Cursor IDE Rules / Skills / Subagents 前端项目配置全指南
前端·ide
音仔小瓜皮29 分钟前
【Vue】什么时候用Ref?什么时候用shallowRef?
前端·javascript·vue.js
码喽7号31 分钟前
vue学习五:前端路由VueRouter
前端·vue.js·学习
史迪仔011233 分钟前
[QML] 交互事件深度解析:鼠标、键盘、拖拽
前端·c++·qt
ZC跨境爬虫37 分钟前
海南大学交友平台开发实战 day11(实现性别图标渲染与后端数据关联+Debug复盘)
前端·python·sqlite·html·json