在JavaScript中复制所选文本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在JavaScript中复制所选文本相关的知识,希望对你有一定的参考价值。

Sometimes you have some information on your page and your visitors might want to copy it. The easiest way is to provide a mechanism that allows them to simply click a button to do so. You have to paste this code into the head of your web page:
  1. <script language="javascript">
  2. function CopyText(el){
  3. var selectedText = "";
  4. if(window.getSelection){
  5. selectedText = window.getSelection();
  6. }else if (document.getSelection){
  7. selectedText = document.getSelection();
  8. }else if (document.selection){
  9. selectedText = document.selection.createRange().text;
  10. }
  11. if(selectedText != ""){
  12. selectedText = selectedText.toString();
  13. el.focus();
  14. el.value = selectedText;
  15. }else {
  16. alert("Select a text in the page and then press this button!");
  17. }
  18. }
  19. </script>
  20.  
  21. Select any part of this text to copy it...
  22. <form name="frmCopyText">
  23. <textarea name="txtSelect" rows="4" cols="45"></textarea><br>
  24. <input onclick="CopyText(this.form.txtSelect)"
  25. type="button"
  26. value="Press to copy the highlighted text"
  27. name="btnCopy">
  28. </form>

以上是关于在JavaScript中复制所选文本的主要内容,如果未能解决你的问题,请参考以下文章

使用JavaScript读取所选文本并将其复制到剪贴板

javascript 复制所选文本

如何使用 javascript 在 getSelection() 中查找所选文本的索引?

C#如何获取comboBox所选的文本内容

JavaScript 复制所选文字

获取所选文本的开始和结束索引? [复制]