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

14,370次阅读
没有评论

共计 1485 个字符,预计需要花费 4 分钟才能阅读完成。

前言

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

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

js:

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

html

  
    

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

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于1970-01-01发表,共计1485字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)