JavaScript

复制到剪贴板

/**
 * 内容复制到剪贴板
 * @param {string} str 需要被复制的内容
 * @param {Function} success 复制成功回调函数
 * @param {Function} failure 复制失败回调函数
 */
function copyToClipboard(str, success, failure) {
  if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(str).then(success).catch(failure);
  } else {
    let el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    if (document.execCommand('copy')) {
      success();
    } else {
      failure();
    }
    document.body.removeChild(el);
  }
}

注意

① Clipboard API 目前仅在 HTTPS 网站上支持;

重命名键