6

JS 实现 点击按钮复制文本到剪贴板中

 2 years ago
source link: https://www.haorooms.com/post/js_copy_text
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

js复制文本到剪切板有很多方法,很多朋友会用开源库,其实纯js的方式实现也很简单。关于复制和剪切板,之前也写过很多文章,例如。 javascript execCommand,复文本框神器 记录一下js光标位置及复制和剪切板 文件上传之剪切板上传及大文件分片上传和断点续传

今天分享一下简单的copy方案。

navigator.clipboard.writeText 方案

这个方案不支持ie,比较简单

var text = 'Example text to appear on clipboard by haorooms.com';
navigator.clipboard.writeText(text).then(
  function () {
    console.log('Haorooms tips: Copying to clipboard was successful!');
  },
  function (err) {
    console.error('haorooms tips: Could not copy text: ', err);
  }
);

document.execCommand(‘copy’)

这些方案博客之前有介绍。可以综合两种方案:

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);
    }
  );
}
var copyBobBtn = document.querySelector('.js-copy-haorooms-btn')

copyBobBtn.addEventListener('click', function (event) {
  copyTextToClipboard(haoroomsinputtext.value);
});
  <input type="text" id="haoroomsinputtext" />
    <button class="js-copy-haorooms-btn">haoroomscopybtn</button>

此demo可以之间copy到html种之间运行。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK