Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

html - javascript copy rich text contents to clipboard

Premise

I need help copying rich text to the clipboard using JavaScript. I have searched around and haven't found anything to suit my specific needs.

Code

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With modern browsers, if you want copy rich text only, there is a very easy solution without using any packages. See http://jsfiddle.net/jdhenckel/km7prgv4/3

Here is the source code from the fiddle

<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>

the function

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);
};

?? ClipboardEvent.clipboardData is experimental technology. Check the browser compatibility table in MDN (05-03-21)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...