javascript字串複製


雖然可以自己複製還是有網站有要求快速複製的按鈕方便使用者使用,記錄一下使用javascript複製字串的方式。

基本上來自stackovefflow,只是稍微調整一點點方便自己使用。
https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript

//複製用函數
function fallbackCopyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;
  
  // Avoid scrolling to bottom
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    //console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    //console.error('Fallback: Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text);
    return;
  }
  navigator.clipboard.writeText(text).then(function() {
    //console.log('Async: Copying to clipboard was successful!');
  }, function(err) {
    //console.error('Async: Could not copy text: ', err);
  });
}

//綁定複製功能
$('.js-copy-btn').click(function(e){
	e.preventDefault();
	copyTextToClipboard("複製的字串");
});
Tags : javascript