Skip to content
LYF edited this page Sep 27, 2017 · 38 revisions
// 复制字符串到剪切板
  function copyTextToClipboard(text, success, error) {
    success = success || function () {};
    error = error || function () {};
    // 如果是IE,就使用IE专有方式进行拷贝
    // 好处是可以直接复制而不用曲线救国,创建textarea来实现。
    if (window.clipboardData) {
      var successful = window.clipboardData.setData('Text', text);
      if (successful) {
        success();
      } else {
        error();
      }
    } else {
      var textArea = document.createElement('textarea');
      var styleArr = [
        'position:', 'fixed;',
        'top:', '0;',
        'left:', '0;',
        'padding:', '0;',
        // 针对safari10
        // 增大textarea的大小,否则的话在safari10中successful为true,
        // 但却什么也没拷贝
        'width:', '31px;',
        'height:', '21px;',
        'border:', 'none;',
        'outline:', 'none;',
        'boxShadow:', 'none;',
        'background:', 'transparent;',
        // 针对safari10
        // 因为增大了textarea的大小,故使用其他技巧隐藏之
        'opacity:', '0;',
        'z-index:', '-1;'
      ];
      textArea.style.cssText = styleArr.join('');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
        try {
          if (successful) {
            success();
          } else {
            error();
          }
        } catch (e) {
          console.log('执行success或error有异常!!!!!');
          console.error(e);
        }
      } catch (e) {
        console.log('Oops, unable to copy');
        error();
      }
      // 卸磨杀驴
      document.body.removeChild(textArea);
    }
  }
Clone this wiki locally