如何使用JavaScript将富文本内容复制到剪贴板?

问题描述 投票:0回答:7

前提

我需要使用 JavaScript 将富文本复制到剪贴板的帮助。我四处搜寻,但没有找到任何适合我的特定需求的东西。

代码

function ctrlA1(corp) {
  with(corp) {}
  if (document.all) {
    txt = corp.createTextRange()
    txt.execCommand("Copy")
  } else
    setTimeout("window.status=''", 5000)
}
<div id="sc1">hello <br> <b> world </b> </div>
<button onclick="ctrlA1(document.getElementById('sc1') )"></button>

问题

上述代码不起作用并导致

object expected error
。任何帮助表示赞赏! 我见过一个名为
zeroclipboard
的库,但更喜欢编写自己的函数。


编辑:

我现在有这个功能来选择页面上的文本。是否可以编写一个公式来按原样复制所选范围?

function containerSelect(id) {
  containerUnselect();
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(id);
    range.select();
  } else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(id);
    window.getSelection().addRange(range);
  }
}
<label onclick="containerSelect(this); select_all()">
  <p>hello world</p>
  <img src="imagepath.png">
</label>

javascript html clipboard
7个回答
97
投票

使用现代浏览器,如果您只想复制富文本,有一个非常简单的解决方案无需使用任何软件包。请参阅http://jsfiddle.net/jdhenckel/km7prgv4/3

这是小提琴的源代码

<button onclick="copyToClip(document.getElementById('foo').innerHTML)">
  Copy the stuff
  </button>
  
<div id=foo style="display:none">
  This is some data that is not visible. 
  You can write some JS to generate this data. 
  It can contain rich stuff.  <b> test </b> me <i> also </i>
  <span style="font: 12px consolas; color: green;">Hello world</span> 
  You can use setData to put TWO COPIES into the same clipboard, 
  one that is plain and one that is rich. 
  That way your users can paste into either a
  <ul>
    <li>plain text editor</li>
    <li>or into a rich text editor</li>
  </ul>
</div>

功能

function copyToClip(str) {
  function listener(e) {
    e.clipboardData.setData("text/html", str);
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  }
  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);
};

⚠️ ClipboardEventclipboardData 是实验性技术。检查 MDN 中的浏览器兼容性表 (05-03-21)


12
投票

这个小小的 JS 插件可以复制富文本而不使用 Flashhttps://www.npmjs.com/package/clipboard-js

它基于 https://clipboardjs.com/ - 但在我看来这是一个升级,因为原始版本仅支持纯文本。

代码很简单:

clipboard.copy({
    "text/html": "<i>Markup</i> <b>text</b>. Paste me into a rich text editor."
});

6
投票

这是我使用新的剪贴板 API 测试的示例:

const content = '<a href="http://google.com/">test</a>';
const blob = new Blob([content], {type: 'text/html'});
const clipboardItem = new window.ClipboardItem({ 'text/html': blob });
navigator.clipboard.write([clipboardItem]);

使用此方法,您可以将html复制到剪贴板。需要注意的一件有用的事情是,这可以包含图像(可以是 dataURL)。这是我发现将多个图像粘贴到剪贴板的唯一方法。



1
投票

这是一个旧的基于 Flash 的解决方案。由于Flash已停产,因此不应再在生产环境中使用。

https://github.com/zeroclipboard/zeroclipboard


0
投票

这是一个简单的函数,它使用支持的 Clipboard API(在我写这篇文章时,除了 Firefox 之外,其他地方都支持),并回退到不支持的

document.execCommand("copy")
方法 (已弃用) ,但目前在所有地方都可以使用),希望 Firefox 在放弃对 execCommand
 的支持之前添加对 Clipboard API 的支持 :)

/** Paste richly formatted text. * * @param {string} rich - the text formatted as HTML * @param {string} plain - a plain text fallback */ async function pasteRich(rich, plain) { if (typeof ClipboardItem !== "undefined") { // Shiny new Clipboard API, not fully supported in Firefox. // https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API#browser_compatibility const html = new Blob([rich], { type: "text/html" }); const text = new Blob([plain], { type: "text/plain" }); const data = new ClipboardItem({ "text/html": html, "text/plain": text }); await navigator.clipboard.write([data]); } else { // Fallback using the deprecated `document.execCommand`. // https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#browser_compatibility const cb = e => { e.clipboardData.setData("text/html", rich); e.clipboardData.setData("text/plain", plain); e.preventDefault(); }; document.addEventListener("copy", cb); document.execCommand("copy"); document.removeEventListener("copy", cb); } }
您可能还想尝试

用于剪贴板 API 的适当的填充


-2
投票
我搜索了一个星期终于找到了答案! 对于那些希望使用 JavaScript 将富文本复制到剪贴板的人,然后使用下面链接中的功能,效果就像一个魅力。 不需要闪光灯和其他建议的东西:)

使用 JavaScript/jquery 将图像复制到剪贴板

© www.soinside.com 2019 - 2024. All rights reserved.