[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.')
    }
}
相关推荐
蓝胖子的多啦A梦2 分钟前
npm : 无法加载文件 C:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚
前端·npm·node.js
LinCC74 分钟前
在Vite中构建项目出错-Top-level await is not available in the configured target environme
前端
咪库咪库咪5 分钟前
js的浅拷贝与深拷贝
javascript
幸福的猪在江湖5 分钟前
第一章:变量筑基 - 内力根基修炼法
javascript
Ryan今天学习了吗5 分钟前
💥不说废话,带你使用原生 JS + HTML 实现超丝滑拖拽排序效果
javascript·html
用户882093216676 分钟前
如何优雅拆分一个充斥十几种逻辑的 SDK 回调函数?
前端
Momoly087 分钟前
vue3+el-table 利用插槽自定义数据样式
前端·javascript·vue.js
多啦C梦a7 分钟前
从 React 初体验到数据驱动的界面开发:一步步解析 Todo List 组件
javascript·react.js
唯有选择7 分钟前
让你的应用界面好看的基石:Flutter主题Theme使用和扩展自定义字段
前端·flutter
山有木兮木有枝_8 分钟前
告别布局间隙:浮动(float)在网页排版中的高阶应用
前端