随笔 - 144  文章 - 0  评论 - 2  阅读 - 19万

JS实现复制富文本到剪贴板/粘贴板的最佳实践

背景

最近有想实现一个功能,通过点击一个button按钮,来复制网页内容(含html)来实现复制后粘贴到邮件或者word具有富文本的效果。在网站翻了一些资料,要么就是方法已经被弃用,要么就是兼容性特别差,要么就是不能复制成为富文本。最后还是通过clipboard-polyfill.js(https://github.com/lgarron/clipboard-polyfill)来解决了问题。下面来介绍怎么使用。

使用
  1. npm install clipboard-polyfill
    然后从node_modules dist文件夹里面找出来核心的js(clipboard-polyfill.js)放于html同级目录。
    在这里插入图片描述
  2. 编写html,实现复制功能。
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>gen_codereview</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
    </script>
    <script src="clipboard-polyfill.js">
    </script>
    <script>
      $(document).ready(function(){
        $("#btn1").click(() =>{
          var item = new clipboard.ClipboardItem({
            "text/html": new Blob(
              [document.getElementById('div1').outerHTML],
              { type: "text/html" }
            )
          });
          clipboard.write([item]);
          alert('复制成功,请前去word粘贴')
        })
      });
    </script>
</head>
<body>
<button id="btn1">
    点击复制如下div内容
</button>
<div contenteditable="true" id="div1" style="font-size: 12px;border: 1px dashed;margin-top: 20px;padding: 10px;width: fit-content;color: red;">
    this is content
</div>
</body>
</html>
  1. 页面展示如下,点击按钮复制。
    在这里插入图片描述
  2. 进入work,粘贴内容效果如下。
    在这里插入图片描述
结语

今天的内容就先分享到这里,使用过程中有什么问题,欢迎下方留言讨论哟。

posted on   黑夜开发者  阅读(658)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示