copy.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. document.getElementById("copyButton").addEventListener("click", function ()
  2. {
  3. copyToClipboard();
  4. });
  5. function copyToClipboard() {
  6. var elem = document.getElementById("numValue");
  7. // create hidden text element, if it doesn't already exist
  8. var targetId = "_hiddenCopyText_";
  9. var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
  10. var origSelectionStart, origSelectionEnd;
  11. if (isInput)
  12. {
  13. // can just use the original source element for the selection and copy
  14. target = elem;
  15. origSelectionStart = elem.selectionStart;
  16. origSelectionEnd = elem.selectionEnd;
  17. } else
  18. {
  19. // must use a temporary form element for the selection and copy
  20. target = document.getElementById(targetId);
  21. if (!target)
  22. {
  23. var target = document.createElement("textarea");
  24. target.style.position = "absolute";
  25. target.style.left = "-9999px";
  26. target.style.top = "0";
  27. target.id = targetId;
  28. document.body.appendChild(target);
  29. }
  30. target.textContent = elem.textContent;
  31. }
  32. // select the content
  33. var currentFocus = document.activeElement;
  34. target.focus();
  35. target.setSelectionRange(0, target.value.length);
  36. // copy the selection
  37. var succeed;
  38. try
  39. {
  40. succeed = document.execCommand("copy");
  41. }
  42. catch (e)
  43. {
  44. succeed = false;
  45. }
  46. // restore original focus
  47. if (currentFocus && typeof currentFocus.focus === "function")
  48. {
  49. currentFocus.focus();
  50. }
  51. if (isInput)
  52. {
  53. // restore prior selection
  54. elem.setSelectionRange(origSelectionStart, origSelectionEnd);
  55. } else
  56. {
  57. // clear temporary content
  58. target.textContent = "";
  59. }
  60. alert("复制成功!");
  61. return succeed;
  62. }