[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.')
    }
}
相关推荐
ole ' ola几秒前
lambda表达式
java·前端·jvm
wefly20176 分钟前
无需安装、开箱即用!m3u8live.cn 在线 HLS 播放器,调试直播流效率翻倍
前端·后端·python·前端开发工具·后端开发工具
UXbot8 分钟前
为什么 AI 正在重新定义 UI 设计工具的入门门槛
前端·人工智能·低代码·ui·交互·ai编程·ux
柳杉22 分钟前
两款惊艳的 WebGL 开源项目推荐
前端·javascript·数据可视化
给算法爸爸上香28 分钟前
web网页显示点云
前端·3d·web·点云
IT_陈寒29 分钟前
React组件性能翻倍的5个冷门技巧,90%的开发者不知道!
前端·人工智能·后端
jingxindeyi36 分钟前
react实现狼吃羊游戏
javascript·react.js·游戏
小金鱼Y2 小时前
别再乱拷贝了!JS 浅拷贝 vs 深拷贝全解析
前端·javascript
kyriewen2 小时前
Sass 进阶:当 CSS 学会了编程,变量函数循环全都安排上
前端·css·scss
海带先森2 小时前
python 虚拟环境的创建
前端