如何使用JavaScript复制到剪贴板?

时间:2008-12-30 13:09:06

标签: javascript clipboard copy-paste

将文字复制到剪贴板的最佳方法是什么? (多浏览器)

我试过了:

function copyToClipboard(text) {
    if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", text);
    } else {  
        unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
        const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);  
        clipboardHelper.copyString(text);
    }
}

但在Internet Explorer中,它会出现语法错误。在Firefox中,它显示unsafeWindow is not defined

没有闪光灯的好方法:How does Trello access the user's clipboard?

62 个答案:

答案 0 :(得分:1859)

概述

有三种主要的浏览器API可用于复制到剪贴板:

  1. Async Clipboard API [navigator.clipboard.writeText]
    • Chrome 66 (March 2018)
    • 中提供了以文字为中心的部分
    • 访问是异步的并使用JavaScript Promises,可以编写,以便安全用户提示(如果显示)不会中断页面​​中的JavaScript。
    • 可以直接从变量将文本复制到剪贴板。
    • 仅支持通过HTTPS提供的网页。
    • 在Chrome中,活动标签页中的66页可以在没有权限提示的情况下写入剪贴板。
  2. document.execCommand('copy')
    • 截至2015年4月,大多数浏览器都支持此功能(请参阅下面的浏览器支持)。
    • 访问是同步的,即在页面中停止JavaScript直到完成,包括显示和用户与任何安全提示进行交互。
    • 从DOM读取文本并将其放在剪贴板上。
    • 在测试期间〜2015年4月,只有Internet Explorer被注意为在写入剪贴板时显示权限提示。
  3. 覆盖复制事件
    • 请参阅Overriding the copy event上的剪贴板API文档。
    • 允许您修改任何复制事件在剪贴板上显示的内容,可以包括纯文本以外的其他格式的数据。
    • 此处未涉及,因为它没有直接回答问题。
  4. 一般发展说明

    当您在控制台中测试代码时,不要期望与剪贴板相关的命令有效。通常,页面必须是活动的(Async Clipboard API)或需要用户交互(例如用户点击)以允许(document.execCommand('copy'))访问剪贴板,请参阅下面的详细信息。

    Async + Fallback

    由于浏览器支持新的Async Clipboard API,您可能希望回退到document.execCommand('copy')方法以获得良好的浏览器覆盖率。

    这是一个简单的例子:

    
    
    function fallbackCopyTextToClipboard(text) {
      var textArea = document.createElement("textarea");
      textArea.value = text;
      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-bob-btn'),
      copyJaneBtn = document.querySelector('.js-copy-jane-btn');
    
    copyBobBtn.addEventListener('click', function(event) {
      copyTextToClipboard('Bob');
    });
    
    
    copyJaneBtn.addEventListener('click', function(event) {
      copyTextToClipboard('Jane');
    });
    
    <div style="display:inline-block; vertical-align:top;">
      <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
      <button class="js-copy-jane-btn">Set clipboard to JANE</button>
    </div>
    <div style="display:inline-block;">
      <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
    
      </textarea>
    </div>
    &#13;
    &#13;
    &#13;

    请注意,此代码段在Stack Overflow的嵌入式预览中效果不佳,您可以在此处尝试:https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011

    异步剪贴板API

    请注意,有能力'#34;请求权限&#34;并通过Chrome 66中的权限API测试访问剪贴板。

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

    document.execCommand(&#39;复印&#39)

    本文的其余部分将介绍document.execCommand('copy') API的细微差别和细节。

    浏览器支持

    JavaScript document.execCommand('copy')支持已经增长,请参阅下面的链接了解浏览器更新:

    简单示例

    &#13;
    &#13;
    var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
    
    copyTextareaBtn.addEventListener('click', function(event) {
      var copyTextarea = document.querySelector('.js-copytextarea');
      copyTextarea.focus();
      copyTextarea.select();
    
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
      } catch (err) {
        console.log('Oops, unable to copy');
      }
    });
    &#13;
    <p>
      <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
      <textarea class="js-copytextarea">Hello I'm some text</textarea>
    </p>
    &#13;
    &#13;
    &#13;

    复杂示例:复制到剪贴板而不显示输入

    如果屏幕上显示textareainput元素,则上述简单示例效果很好。

    在某些情况下,您可能希望将文本复制到剪贴板而不显示input / textarea元素。这是解决此问题的一种方法示例(基本上是插入元素,复制到剪贴板,删除元素):

    使用Google Chrome 44,Firefox 42.0a1和Internet Explorer 11.0.8600.17814进行测试。

    &#13;
    &#13;
    function copyTextToClipboard(text) {
      var textArea = document.createElement("textarea");
    
      //
      // *** This styling is an extra step which is likely not required. ***
      //
      // Why is it here? To ensure:
      // 1. the element is able to have focus and selection.
      // 2. if element was to flash render it has minimal visual impact.
      // 3. less flakyness with selection and copying which **might** occur if
      //    the textarea element is not visible.
      //
      // The likelihood is the element won't even render, not even a
      // flash, so some of these are just precautions. However in
      // Internet Explorer the element is visible whilst the popup
      // box asking the user for permission for the web page to
      // copy to the clipboard.
      //
    
      // Place in top-left corner of screen regardless of scroll position.
      textArea.style.position = 'fixed';
      textArea.style.top = 0;
      textArea.style.left = 0;
    
      // Ensure it has a small width and height. Setting to 1px / 1em
      // doesn't work as this gives a negative w/h on some browsers.
      textArea.style.width = '2em';
      textArea.style.height = '2em';
    
      // We don't need padding, reducing the size if it does flash render.
      textArea.style.padding = 0;
    
      // Clean up any borders.
      textArea.style.border = 'none';
      textArea.style.outline = 'none';
      textArea.style.boxShadow = 'none';
    
      // Avoid flash of white box if rendered for any reason.
      textArea.style.background = 'transparent';
    
    
      textArea.value = text;
    
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
    
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
      } catch (err) {
        console.log('Oops, unable to copy');
      }
    
      document.body.removeChild(textArea);
    }
    
    
    var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
      copyJaneBtn = document.querySelector('.js-copy-jane-btn');
    
    copyBobBtn.addEventListener('click', function(event) {
      copyTextToClipboard('Bob');
    });
    
    
    copyJaneBtn.addEventListener('click', function(event) {
      copyTextToClipboard('Jane');
    });
    &#13;
    <div style="display:inline-block; vertical-align:top;">
      <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
      <button class="js-copy-jane-btn">Set clipboard to JANE</button>
    </div>
    <div style="display:inline-block;">
      <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
    
      </textarea>
    </div>
    &#13;
    &#13;
    &#13;

    附加说明

    仅在用户执行操作

    时有效

    所有document.execCommand('copy')来电都必须是用户操作的直接结果,例如点击事件处理程序这是一种措施,可以防止在用户不期望的情况下弄乱用户的剪贴板。

    有关详细信息,请参阅Google Developers post here

    剪贴板API

    注意完整的Clipboard API草案规范可以在这里找到: https://w3c.github.io/clipboard-apis/

    是否支持?

      如果浏览器支持命令&#34;,则
    • document.queryCommandSupported('copy')应返回true
    • 如果现在调用document.queryCommandEnabled('copy')成功,则
    • true返回document.execCommand('copy')。检查以确保从用户启动的线程调用该命令并满足其他要求。

    但是,作为浏览器兼容性问题的示例,如果从用户启动的线程调用该命令,则从2015年4月到10月的Google Chrome仅从true返回document.queryCommandSupported('copy')

    请注意下面的兼容性详细信息。

    浏览器兼容性详细信息

    虽然通过用户点击调用document.execCommand('copy') / try块中包含的catch的简单调用可以获得最大的兼容性,但以下是一些附带条款:< / p>

    document.execCommanddocument.queryCommandSupporteddocument.queryCommandEnabled的任何来电都应包含在try / catch块中。

    不同的浏览器实现和浏览器版本在调用时会抛出不同类型的异常,而不是返回false

    不同的浏览器实现仍在不断变化,Clipboard API仍在草案中,所以请记住进行测试。

答案 1 :(得分:1230)

自动复制到剪贴板可能很危险,因此大多数浏览器(IE除外)都非常困难。就个人而言,我使用以下简单的技巧:

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

向用户显示提示框,其中已选择要复制的文本。现在足以按 Ctrl + C 输入(关闭方框) - 瞧!

现在剪贴板复制操作是SAFE,因为用户手动执行(但是以非常简单的方式)。当然,适用于所有浏览器。

<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>

<script>
  function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
</script>

答案 2 :(得分:229)

以下方法适用于Chrome,Firefox,Internet Explorer和Edge以及最新版本的Safari(复制支持已在2016年10月发布的版本10中添加)。

  • 创建一个textarea并将其内容设置为您要复制到剪贴板的文本。
  • 将textarea附加到DOM。
  • 选择textarea中的文字。
  • 调用document.execCommand(“copy”)
  • 从dom中删除textarea。

注意:您将看不到textarea,因为它是在Javascript代码的同一个同步调用中添加和删除的。

如果您自己实施,请注意以下事项:

  • 出于安全原因,这只能从事件处理程序中调用,例如单击(就像打开窗口一样)。
  • IE将在第一次更新剪贴板时显示权限对话框。
  • IE,当textarea聚焦时,Edge将滚动。
  • execCommand()可能会抛出某些情况。
  • 除非您使用textarea,否则可能会吞下新行和制表符。 (大多数文章似乎建议使用div)
  • 显示IE对话框时将显示textarea,您需要隐藏它,或使用IE特定的clipboardData api。
  • 在IE系统中,管理员可以禁用剪贴板API。

以下功能应尽可能干净地处理以下所有问题。如果您发现任何问题或有任何改进建议,请发表评论。

$('.form-sending-gif').show()

https://jsfiddle.net/fx6a6n6x/

答案 3 :(得分:93)

如果你想要一个非常简单的解决方案(整合时间不到5分钟)并且开箱即用,那么Clippy是一些比较复杂的解决方案的不错选择。

它是由GitHub的联合创始人撰写的。示例Flash嵌入代码如下:

<object
   classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   width="110"
   height="14"
   id="clippy">
  <param name="movie" value="/flash/clippy.swf"/>
  <param name="allowScriptAccess" value="always"/>
  <param name="quality" value="high"/>
  <param name="scale" value="noscale"/>
  <param NAME="FlashVars" value="text=#{text}"/>
  <param name="bgcolor" value="#{bgcolor}"/>
  <embed
     src="/flash/clippy.swf"
     width="110"
     height="14"
     name="clippy"
     quality="high"
     allowScriptAccess="always"
     type="application/x-shockwave-flash"
     pluginspage="http://www.macromedia.com/go/getflashplayer"
     FlashVars="text=#{text}"
     bgcolor="#{bgcolor}"/>
</object>

请务必将#{text}替换为您需要复制的文字,并#{bgcolor}替换为彩色。

答案 4 :(得分:80)

从网页读取和修改剪贴板会引发安全和隐私问题。但是,在Internet Explorer中,可以执行此操作。我找到了example snippet

    <script type="text/javascript">
        function select_all(obj) {
            var text_val=eval(obj);
            text_val.focus();
            text_val.select();
            r = text_val.createTextRange();
            if (!r.execCommand) return; // feature detection
            r.execCommand('copy');
        }
    </script>
    <input value="http://www.sajithmr.com"
     onclick="select_all(this)" name="url" type="text" />

答案 5 :(得分:67)

我最近在这个问题上写了technical blog post(我在Lucidchart工作,最近我们在剪贴板上进行了大修)。

将纯文本复制到剪贴板相对简单,假设您想在系统复制事件期间执行此操作(用户按 Ctrl C 或使用浏览器&#39; s菜单)。

var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1 
           || navigator.userAgent.toLowerCase().indexOf("trident") != -1);

document.addEventListener('copy', function(e) {
    var textToPutOnClipboard = "This is some text";
    if (isIe) {
        window.clipboardData.setData('Text', textToPutOnClipboard);    
    } else {
        e.clipboardData.setData('text/plain', textToPutOnClipboard);
    }
    e.preventDefault();
});

在系统复制事件期间不将文本放在剪贴板上要困难得多。看起来这些其他答案中的一些提到了通过Flash实现它的方法,这是唯一的跨浏览器方式(据我所知)。

除此之外,还有一些基于浏览器的选项。

这是IE中最简单的,您可以随时通过JavaScript访问clipboardData对象:

window.clipboardData

(当您尝试在系统剪切,复制或粘贴事件之外执行此操作时,IE将提示用户授予Web应用程序剪贴板权限。)

在Chrome中,您可以创建一个Chrome扩展程序,为您提供clipboard permissions(这就是我们为Lucidchart所做的工作)。然后,对于安装了扩展程序的用户,您只需要自己触发系统事件:

document.execCommand('copy');

Firefox似乎some options允许用户授予某些网站访问剪贴板的权限,但我还没有尝试过这些内容。

答案 6 :(得分:46)

这是我对那个人的看法..

  constructor() {
    super().node = this.render();  
  }

答案 7 :(得分:46)

clipboard.js是一个小型的非Flash实用程序,允许将文本或HTML数据复制到剪贴板。它非常容易使用,只需包含.js并使用以下内容:

<button id='markup-copy'>Copy Button</button>

<script>
document.getElementById('markup-copy').addEventListener('click', function() {
  clipboard.copy({
    'text/plain': 'Markup text. Paste me into a rich text editor.',
    'text/html': '<i>here</i> is some <b>rich text</b>'
  }).then(
    function(){console.log('success'); },
    function(err){console.log('failure', err);
  });

});
</script>

clipboard.js也在GitHub上。

  

注意:现在已弃用。迁移到here

答案 8 :(得分:34)

ZeroClipboard是我发现的最佳跨浏览器解决方案:

<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>    
<script src="ZeroClipboard.js"></script>
<script>
  var clip = new ZeroClipboard( document.getElementById('copy') );
</script>

如果你需要iOS的非Flash支持,你只需添加一个后备:

clip.on( 'noflash', function ( client, args ) {
    $("#copy").click(function(){            
        var txt = $(this).attr('data-clipboard-text');
        prompt ("Copy link, then click OK.", txt);
    });
});  

http://zeroclipboard.org/

https://github.com/zeroclipboard/ZeroClipboard

答案 9 :(得分:25)

我正在研究的一个项目,一个利用Zero Clipboard库的jQuery复制到剪贴板插件。

如果你是一个沉重的jQuery用户,它比原生的Zero Clipboard插件更容易使用。

答案 10 :(得分:23)

    $("td").click(function (e) {
        var clickedCell = $(e.target).closest("td");
        navigator.clipboard.writeText(clickedCell.text());
        alert(clickedCell.text());
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>First<td>
</tr>
<tr>
<td>Second<td>
</tr>
<tr>
<td>Third<td>
</tr>
<tr>
<td>Fourth<td>
</tr>
</table>

我已经阅读了所有答案,截至2020年6月1日,当我终于找到文档时,我一直在努力解决这个问题:

$("td").click(function (e) {
    var clickedCell = $(e.target).closest("td");
    navigator.clipboard.writeText(clickedCell.text());
});

它将单击的单元格文本写入浏览器剪贴板。

您可以根据需要更改选择器“ td”,可以添加console.log进行调试和/或警报功能。

以下是文档: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText

答案 11 :(得分:21)

Geesh,不确定为什么还没有人指出这一点。

伙计们,在2018年,您可以按照以下方法进行操作:

async copySomething(text?) {
  try {
    const toCopy = text || location.href;
    await navigator.clipboard.writeText(toCopy);
    console.log('Text or Page URL copied');
  } catch (err) {
    console.error('Failed to copy: ', err);
  }
}

在我的Angular 6+代码中使用,如下所示:

<button mat-menu-item (click)="copySomething()">
    <span>Copy link</span>
</button>

如果我输入一个字符串,它将复制它。如果没有,则复制页面的URL。

也可以对剪贴板进行更多的体操练习。在此处查看更多信息:

https://developers.google.com/web/updates/2018/03/clipboardapi

答案 12 :(得分:21)

我找到了以下解决方案:

On key down handler创建“pre”标签。我们将内容设置为复制到此标记,然后对此标记进行选择并在处理程序中返回true。这会调用chrome的标准处理程序并复制所选文本。

如果需要,可以设置恢复先前选择的功能超时。我在Mootools上的实现:

   function EnybyClipboard() {
     this.saveSelection = false;
     this.callback = false;
     this.pastedText = false;

     this.restoreSelection = function() {
       if (this.saveSelection) {
         window.getSelection().removeAllRanges();
         for (var i = 0; i < this.saveSelection.length; i++) {
           window.getSelection().addRange(this.saveSelection[i]);
         }
         this.saveSelection = false;
       }
     };

     this.copyText = function(text) {
       var div = $('special_copy');
       if (!div) {
         div = new Element('pre', {
           'id': 'special_copy',
           'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
         });
         div.injectInside(document.body);
       }
       div.set('text', text);
       if (document.createRange) {
         var rng = document.createRange();
         rng.selectNodeContents(div);
         this.saveSelection = [];
         var selection = window.getSelection();
         for (var i = 0; i < selection.rangeCount; i++) {
           this.saveSelection[i] = selection.getRangeAt(i);
         }
         window.getSelection().removeAllRanges();
         window.getSelection().addRange(rng);
         setTimeout(this.restoreSelection.bind(this), 100);
       } else return alert('Copy not work. :(');
     };

     this.getPastedText = function() {
       if (!this.pastedText) alert('Nothing to paste. :(');
       return this.pastedText;
     };

     this.pasteText = function(callback) {
       var div = $('special_paste');
       if (!div) {
         div = new Element('textarea', {
           'id': 'special_paste',
           'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
         });
         div.injectInside(document.body);
         div.addEvent('keyup', function() {
           if (this.callback) {
             this.pastedText = $('special_paste').get('value');
             this.callback.call(null, this.pastedText);
             this.callback = false;
             this.pastedText = false;
             setTimeout(this.restoreSelection.bind(this), 100);
           }
         }.bind(this));
       }
       div.set('value', '');
       if (document.createRange) {
         var rng = document.createRange();
         rng.selectNodeContents(div);
         this.saveSelection = [];
         var selection = window.getSelection();
         for (var i = 0; i < selection.rangeCount; i++) {
           this.saveSelection[i] = selection.getRangeAt(i);
         }
         window.getSelection().removeAllRanges();
         window.getSelection().addRange(rng);
         div.focus();
         this.callback = callback;
       } else return alert('Fail to paste. :(');
     };
   }

用法:

enyby_clip = new EnybyClipboard(); //init 

enyby_clip.copyText('some_text'); // place this in CTRL+C handler and return true;

enyby_clip.pasteText(function callback(pasted_text) {
        alert(pasted_text);
}); // place this in CTRL+V handler and return true;

在粘贴时,它会创建textarea并以相同的方式工作。

PS可能是这个解决方案可用于创建完全跨浏览器的解决方案,无需flash。它适用于FF和Chrome。

答案 13 :(得分:19)

我非常成功地使用了它(没有 jquery或任何其他框架)。

function copyToClp(txt){
    txt = document.createTextNode(txt);
    var m = document;
    var w = window;
    var b = m.body;
    b.appendChild(txt);
    if (b.createTextRange) {
        var d = b.createTextRange();
        d.moveToElementText(txt);
        d.select();
        m.execCommand('copy');
    } else {
        var d = m.createRange();
        var g = w.getSelection;
        d.selectNodeContents(txt);
        g().removeAllRanges();
        g().addRange(d);
        m.execCommand('copy');
        g().removeAllRanges();
    }
    txt.remove();
} 

警告

制表符将转换为空格(至少在Chrome中为空)。

答案 14 :(得分:19)

其他方法会将纯文本复制到剪贴板。要复制HTML(即,您可以将结果粘贴到WSIWYG编辑器中),您可以在 IE ONLY 中执行以下操作。这与其他方法根本不同,因为浏览器实际上可以明显地选择内容。

// create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
    contentEditable = true;
}     
editableDiv.appendChild(someContentElement);          

// select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();  
r.execCommand("Copy");

// deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();   

答案 15 :(得分:19)

最近Chrome 42+Firefox 41+现在支持 document.execCommand('copy')命令。因此,我使用Tim Down's old answerGoogle Developer's answer的组合为跨浏览器复制到剪贴板功能创建了几个函数:

function selectElementContents(el) {
    // Copy textarea, pre, div, etc.
    if (document.body.createTextRange) {
        // IE 
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
        textRange.execCommand("Copy");
    } else if (window.getSelection && document.createRange) {
        // non-IE
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy command was ' + msg);
        } catch (err) {
            console.log('Oops, unable to copy');
        }
    }
} // end function selectElementContents(el) 

function make_copy_button(el) {
    var copy_btn = document.createElement('input');
    copy_btn.type = "button";
    el.parentNode.insertBefore(copy_btn, el.nextSibling);
    copy_btn.onclick = function() {
        selectElementContents(el);
    };

    if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {
        // Copy works with IE 4+, Chrome 42+, Firefox 41+, Opera 29+
        copy_btn.value = "Copy to Clipboard";
    } else {
        // Select only for Safari and older Chrome, Firefox and Opera
        copy_btn.value = "Select All (then press CTRL+C to Copy)";
    }
}
/* Note: document.queryCommandSupported("copy") should return "true" on browsers that support copy
	but there was a bug in Chrome versions 42 to 47 that makes it return "false".  So in those
	versions of Chrome feature detection does not work!
	See https://code.google.com/p/chromium/issues/detail?id=476508
*/

make_copy_button(document.getElementById("markup"));
<pre id="markup">
  Text that can be copied or selected with cross browser support.
</pre>

答案 16 :(得分:12)

从Flash 10开始,如果操作源自用户与Flash对象的交互,则只能复制到剪贴板。 (Read related section from Adobe's Flash 10 announcement

解决方案是在Copy按钮上方过度使用flash对象,或者启动副本的任何元素。零剪贴板目前是具有此实现的最佳库。有经验的Flash开发人员可能只想创建自己的库。

答案 17 :(得分:12)

我把我认为最好的东西放在一起。

  • 使用cssText避免IE中的异常,而不是直接使用样式。
  • 如果有一个
  • ,则恢复选择
  • 设置只读,因此键盘不会出现在移动设备上
  • 有适用于iOS的解决方法,因此它实际上可以正常阻止execCommand。

这是:

const copyToClipboard = (function initClipboardText() {
  const textarea = document.createElement('textarea');

  // Move it off screen.
  textarea.style.cssText = 'position: absolute; left: -99999em';

  // Set to readonly to prevent mobile devices opening a keyboard when
  // text is .select()'ed.
  textarea.setAttribute('readonly', true);

  document.body.appendChild(textarea);

  return function setClipboardText(text) {
    textarea.value = text;

    // Check if there is any content selected previously.
    const selected = document.getSelection().rangeCount > 0 ?
      document.getSelection().getRangeAt(0) : false;

    // iOS Safari blocks programmtic execCommand copying normally, without this hack.
    // https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
    if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
      const editable = textarea.contentEditable;
      textarea.contentEditable = true;
      const range = document.createRange();
      range.selectNodeContents(textarea);
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      textarea.setSelectionRange(0, 999999);
      textarea.contentEditable = editable;
    } else {
      textarea.select();
    }

    try {
      const result = document.execCommand('copy');

      // Restore previous selection.
      if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
      }

      return result;
    } catch (err) {
      return false;
    }
  };
})();

用法:copyToClipboard('some text')

答案 18 :(得分:12)

&#13;
&#13;
  <!DOCTYPE html>

  <style>
    #t {
      width: 1px
      height: 1px
      border: none
    }
    #t:focus {
      outline: none
    }
  </style>

  <script>
    function copy(text) {
      var t = document.getElementById('t')
      t.innerHTML = text
      t.select()
      try {
        var successful = document.execCommand('copy')
        var msg = successful ? 'successfully' : 'unsuccessfully'
        console.log('text coppied ' + msg)
      } catch (err) {
        console.log('Unable to copy text')
      }
      t.innerHTML = ''
    }
  </script>

  <textarea id=t></textarea>

  <button onclick="copy('hello world')">
    Click me
  </button>
&#13;
&#13;
&#13;

答案 19 :(得分:11)

我找到了以下解决方案:

我将文本隐藏在输入中。因为setSelectionRange不能对隐藏的输入起作用,所以我暂时将类型更改为文本,复制文本然后再次隐藏它。如果要复制元素中的文本,可以将其传递给函数并将其内容保存在目标变量中。

    jQuery('#copy').on('click', function () {
        copyToClipboard();
    });

    function copyToClipboard() {
        var target = jQuery('#hidden_text');

        // make it visible, so can be focused
        target.attr('type', 'text');
        target.focus();
        // select all the text
        target[0].setSelectionRange(0, target.val().length);

        // copy the selection
        var succeed;
        try {
            succeed = document.execCommand("copy");
        } catch (e) {
            succeed = false;
        }

        // hide input again
        target.attr('type', 'hidden');

        return succeed;
    }

答案 20 :(得分:11)

此代码在 2021 年 5 月进行了测试。在 Chrome、IE、Edge 上工作。下面的'message'参数是你要复制的字符串值。

<script type="text/javascript">
    function copyToClipboard(message) {
        var textArea = document.createElement("textarea");
        textArea.value = message;
        textArea.style.opacity = "0"; 
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();


        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            alert('Copying text command was ' + msg);
        } catch (err) {
            alert('Unable to copy value , error : ' + err.message);
        }

        document.body.removeChild(textArea);
    }

</script>

答案 21 :(得分:10)

将文本从HTML输入复制到剪贴板

  

&#13;
&#13;
 
 function myFunction() {
  /* Get the text field */
   var copyText = document.getElementById("myInput");
 
   /* Select the text field */
   copyText.select();

   /* Copy the text inside the text field */
   document.execCommand("Copy");
 
   /* Alert the copied text */
   alert("Copied the text: " + copyText.value);
 }
 
&#13;
 
 <!-- The text field -->
 <input type="text" value="Hello Friend" id="myInput">
 
 <!-- The button used to copy the text -->
<button onclick="myFunction()">Copy text</button>
 
&#13;
&#13;
&#13;

     

注意: IE9及更早版本不支持document.execCommand()方法。

来源W3Schools - Copy Text to Clipboard

答案 22 :(得分:9)

在IE以外的浏览器中,您需要使用小型Flash对象来操作剪贴板,例如

答案 23 :(得分:8)

我从(像Excel这样的东西)构建自定义网格编辑和与Excel的兼容性时遇到了同样的问题。我不得不支持选择多个单元格,复制和粘贴。

解决方案:创建一个textarea,您将插入数据供用户复制(对于我当用户选择单元格时),设置焦点(例如,当用户按 Ctrl 时)并选择整个文本。

因此,当用户点击 Ctrl + C 时,他/她会复制他/她选择的单元格。测试后只需将textarea调整为一个像素(我没有测试它是否将在显示器上工作:无)。它适用于所有浏览器,对用户来说是透明的。

粘贴 - 你可以这样做(你的目标不同) - 继续关注textarea并使用onpaste捕捉粘贴事件(在我的项目中,我使用单元格中的textareas进行编辑)。

我无法粘贴示例(商业项目),但您明白了。

答案 24 :(得分:7)

我用过clipboard.js

我们可以在npm

获得它
npm install clipboard --save

还有凉亭

bower install clipboard --save

用法&amp;示例位于https://zenorocha.github.io/clipboard.js/

答案 25 :(得分:7)

已经有很多答案,但我想添加一个(jQuery)。在任何浏览器上都可以像魅力一样工作,也可以在移动浏览器上工作(即提示有关安全性但是当你接受它时工作正常)。

function appCopyToClipBoard( sText )
{
 var oText = false,
     bResult = false;
 try
 {
  oText = document.createElement("textarea");
  $(oText).addClass('clipboardCopier').val(sText).insertAfter('body').focus();
  oText.select();
  document.execCommand("Copy");
  bResult = true;
 } catch(e) {}

 $(oText).remove();
 return bResult;
}

在您的代码中:

if( !appCopyToClipBoard( 'Hai there! This is copied to the clipboard.' ))
 { alert('Sorry, copy to clipboard failed.'); }

答案 26 :(得分:6)

这是@ Chase答案的扩展,其优势在于它适用于IMAGE和TABLE元素,而不仅仅是IE9上的DIV。

if (document.createRange) {
    // IE9 and modern browsers
    var r = document.createRange();
    r.setStartBefore(to_copy);
    r.setEndAfter(to_copy);
    r.selectNode(to_copy);
    var sel = window.getSelection();
    sel.addRange(r);
    document.execCommand('Copy');  // does nothing on FF
} else {
    // IE 8 and earlier.  This stuff won't work on IE9.
    // (unless forced into a backward compatibility mode,
    // or selecting plain divs, not img or table). 
    var r = document.body.createTextRange();
    r.moveToElementText(to_copy);
    r.select()
    r.execCommand('Copy');
}

答案 27 :(得分:5)

这是其他答案之间的一些组合。

var copyToClipboard = function(textToCopy){
    $("body")
        .append($('<input type="text" name="fname" class="textToCopyInput"/>' )
        .val(textToCopy))
        .find(".textToCopyInput")
        .select();
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        alert('Text copied to clipboard!');
      } catch (err) {
          window.prompt("To copy the text to clipboard: Ctrl+C, Enter", textToCopy);
      }
     $(".textToCopyInput").remove();
}

它使用jQuery,但它当然不是必须的。如果需要,您可以更改它。我刚才有jQuery供我使用。您还可以添加一些CSS以确保输入不显示。例如:

.textToCopyInput{opacity: 0; position: absolute;}

当然你也可以做一些内联样式

.append($('<input type="text" name="fname" style="opacity: 0;  position: absolute;" class="textToCopyInput"/>' )

答案 28 :(得分:5)

要将选定的文本(&#39;要复制的文本&#39;)复制到剪贴板,请创建一个Bookmarklet(执行Javsacript的浏览器书签)并执行它(单击它)。 它将创建一个临时文本区域。

Github的代码:

https://gist.github.com/stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d

(function (text) {
  var node = document.createElement('textarea');
  var selection = document.getSelection();

  node.textContent = text;
  document.body.appendChild(node);

  selection.removeAllRanges();
  node.select();
  document.execCommand('copy');

  selection.removeAllRanges();
  document.body.removeChild(node);
})('Text To Copy');

答案 29 :(得分:5)

这是我在互联网上查找各种方式后唯一能够工作的东西。这是一个混乱的话题。世界各地发布了大量解决方案,其中大多数都不起作用。这对我有用:

注意:此代码仅在作为直接同步代码执行时才能用于“onClick&#39;方法。如果您调用异步响应ajax或任何其他异步方式它将无法正常工作

render()

我确实意识到这段代码会在屏幕上显示一个1px宽的组件,显示毫秒,但决定不要担心,这是其他人可以解决的问题。

答案 30 :(得分:5)

似乎我误解了这个问题,但作为参考,你可以提取一系列DOM(不是剪贴板;与所有现代浏览器兼容),并将它与oncopy和onpaste以及onbeforepaste事件结合起来以获得剪贴板行为。以下是实现此目的的代码:

function clipBoard(sCommand) {
  var oRange=contentDocument.createRange();
  oRange.setStart(startNode, startOffset);
  oRange.setEnd(endNode, endOffset);
/* This is where the actual selection happens.
in the above, startNode and endNode are dom nodes defining the beginning 
and end of the "selection" respectively. startOffset and endOffset are 
constants that are defined as follows:

END_TO_END: 2
END_TO_START: 3
NODE_AFTER: 1
NODE_BEFORE: 0
NODE_BEFORE_AND_AFTER: 2
NODE_INSIDE: 3
START_TO_END: 1
START_TO_START: 0

and would be used like oRange.START_TO_END */
      switch(sCommand) {
    case "cut":
          this.oFragment=oRange.extractContents();
      oRange.collapse();
      break;
    case "copy":
      this.oFragment=oRange.cloneContents();
      break;
    case "paste":
      oRange.deleteContents();
      var cloneFragment=this.oFragment.cloneNode(true)
      oRange.insertNode(cloneFragment);
      oRange.collapse();
      break;
  }
}

答案 31 :(得分:5)

我的坏。这仅适用于IE。

这是另一种复制文字的方法:

<p>
    <a onclick="window.clipboardData.setData('text', document.getElementById('Test').innerText);">Copy</a>
</p>

答案 32 :(得分:4)

我必须从页面复制非输入框文本(任何div / span标记内的文本),并提供以下代码。唯一的技巧是拥有隐藏字段,但作为TEXT类型,不会使用隐藏类型。

    function copyToClipboard(sID) {
        var aField = document.getElementById("hiddenField");

        aField.hidden   = false;
        aField.value    = document.getElementById(sID).textContent;
        aField.select();
        document.execCommand("copy");
        alert("Following text has been copied to the clipboard.\n\n" + aField.value);
        aField.hidden = true;
    }

在HTML中添加以下内容

输入类型=&#34;文字&#34; ID =&#34; hiddenField&#34;风格=&#34;宽度:5像素;边界:0&#34; /&GT; ...

答案 33 :(得分:4)

据我所知,只能在Internet Explorer中使用。

另请参阅 Dynamic Tools - JavaScript Copy To Clipboard ,但它要求用户首先更改配置,即使这样,它似乎也无法正常工作。

答案 34 :(得分:4)

您似乎从Greasemonkey\JavaScript Copy to Clipboard button或此代码段的原始来源获取了代码......

此代码适用于Greasemonkey,因此是不安全的窗口。我猜IE中的语法错误来自const关键字,该关键字特定于Firefox(将其替换为var)。

答案 35 :(得分:3)

出于安全原因,您无法做到这一点。您必须选择Flash才能复制到剪贴板。

我建议这一个:http://zeroclipboard.org/

答案 36 :(得分:3)

找到此解决方案here。 Internet Explorer 8和更早版本不支持document.execCommand("copy");

const copyBtn =  document.getElementById("copyBtn");
const input = document.getElementById("input");

function copyText() {
  const value = input.value;
  
  input.select(); // selects the input variable as the text to be copied
  input.setSelectionRange(0, 99999); // this is used to set the selection range for mobile devices
  
  document.execCommand("copy"); // copies the selected text
  
  alert("Copied the text " + value); // displays the copied text in a prompt
}

copyBtn.onmousedown = function () {
  copyText();
}
<input type="text" id="input" placeholder="Type text to copy... "/>
<button id="copyBtn">
  Copy
</button>

答案 37 :(得分:3)

我打算使用clipboard.js,但它还没有任何移动解决方案(还)...所以我写了一个超小型库:

https://github.com/ryanpcmcquen/cheval

这将复制文本(Desktop / Android / Safari 10+),或者至少选择文本(iOS的旧版本)。缩小它只是超过1kB。在桌面Safari中(按Command + C进行复制。您也不需要编写任何JavaScript来使用它。

答案 38 :(得分:3)

2015年更新:目前有一种方法可以使用document.execCommand来处理剪贴板。 clipboard.js提供了一种跨浏览器方式来处理剪贴板(browser support

答案 39 :(得分:2)

如果复制的链接必须粘贴在同一个站点上,那么一个简单的解决方案是在按下简单的HTML复制按钮之前突出显示文本,然后在按下它时,文本内容存储在会话中。无论粘贴在哪里,都有一个粘贴按钮。

**我知道,这不是一个持久且通用的解决方案,但它是:)

答案 40 :(得分:2)

如果您在Chrome扩展程序中从剪贴板中读取文字,并且允许“clipboardRead”权限,则可以使用以下代码:

function readTextFromClipboardInChromeExtension() {
    var ta = $('<textarea/>');
    $('body').append(ta);
    ta.focus();
    document.execCommand('paste');
    var text = ta.val();
    ta.blur();
    ta.remove();
    return text;
}

答案 41 :(得分:2)

使用try/catch使用Javascript功能,您甚至可以更好地处理错误,如下所示:

 copyToClipboard() {
     let el = document.getElementById('Test').innerText
     el.focus(); // el.select();
     try {
         var successful = document.execCommand('copy');
         if (successful) {
             console.log('Copied Successfully! Do whatever you want next');
         } else {
             throw ('Unable to copy');
         }
     } catch (err) {
         console.warn('Oops, Something went wrong ', err);
     }
 }

答案 42 :(得分:2)

除了Dean Taylor's updated answer (July 2015)之外,我还写了一个类似他的例子的jQuery方法。

jsFiddle

/**
* Copies the current selected text to the SO clipboard
* This method must be called from an event to work with `execCommand()`
* @param {String} text Text to copy
* @param {Boolean} [fallback] Set to true shows a prompt
* @return Boolean Returns `true` if the text was copied or the user clicked on accept (in prompt), `false` otherwise
*/
var CopyToClipboard = function(text, fallback){
    var fb = function () {
        $t.remove();
        if (fallback !== undefined && fallback) {
            var fs = 'Please, copy the following text:';
            if (window.prompt(fs, text) !== null) return true;
        }
        return false;
    };
    var $t = $('<textarea />');
    $t.val(text).css({
        width: '100px',
        height: '40px'
    }).appendTo('body');
    $t.select();
    try {
        if (document.execCommand('copy')) {
            $t.remove();
            return true;
        }
        fb();
    }
    catch (e) {
        fb();
    }
};

答案 43 :(得分:2)

在Chrome中,您可以使用copy('the text or variable etc')。虽然这不是跨浏览器(和doesn't work in a snippet?),但您可以将其添加到其他跨浏览器的答案中。

答案 44 :(得分:2)

@Jimbo,这是同一网站的基于Ajax /会话的简单剪贴板。

请注意,必须启用会话&amp;有效,此解决方案适用于同一站点。我在CodeIgniter上测试了它,但是遇到了session / Ajax问题,但this也解决了这个问题。如果您不想使用会话,请使用数据库表。

<强>的JavaScript / jQuery的

<script type="text/javascript">
    $(document).ready(function() {

        $("#copy_btn_id").click(function(){

            $.post("<?php echo base_url();?>ajax/foo_copy/"+$(this).val(), null,
                function(data){
                    // Copied successfully
                }, "html"
            );
        });

        $("#paste_btn_id").click(function() {

           $.post("<?php echo base_url();?>ajax/foo_paste/", null,
               function(data) {
                   $('#paste_btn_id').val(data);
               }, "html"
           );
        });
    });
</script>

HTML内容

<input type='text' id='copy_btn_id' onclick='this.select();'  value='myvalue' />
<input type='text' id='paste_btn_id' value='' />

PHP代码

<?php
    class Ajax extends CI_Controller {

        public function foo_copy($val){
            $this->session->set_userdata(array('clipboard_val' => $val));
        }

        public function foo_paste(){
            echo $this->session->userdata('clipboard_val');
            exit();
        }
    }
?>

答案 45 :(得分:1)

搜索支持Safari和其他浏览器的解决方案(IE9 +)后,

我使用与Github相同的内容:ZeroClipboard

示例:

http://zeroclipboard.org/index-v1.x.html

<强> HTML

<html>
  <body>
    <button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button>
    <script src="ZeroClipboard.js"></script>
    <script src="main.js"></script>
  </body>
</html>

<强> JS

var client = new ZeroClipboard(document.getElementById("copy-button"));

client.on("ready", function (readyEvent) {
    // alert( "ZeroClipboard SWF is ready!" );

    client.on("aftercopy", function (event) {
        // `this` === `client`
        // `event.target` === the element that was clicked
        event.target.style.display = "none";
        alert("Copied text to clipboard: " + event.data["text/plain"]);
    });
});

答案 46 :(得分:1)

这是一个独立的类,通过将其放置在屏幕外,可确保从临时textarea不会出现闪烁。

这可在Safari(台式机),FF和Chrome中使用。

// ================================================================================
// ClipboardClass
// ================================================================================
var ClipboardClass = (function() {


   function copyText(text) {
        // Create temp element off-screen to hold text.
        var tempElem = $('<textarea style="position: absolute; top: -8888px; left: -8888px">');
        $("body").append(tempElem);

        tempElem.val(text).select();
        document.execCommand("copy");
        tempElem.remove();
   }


   // ============================================================================
   // Class API
   // ============================================================================
    return {
        copyText: copyText
    };
})();

答案 47 :(得分:1)

这是一个简单的例子;)

<!DOCTYPE html>
<html>
    <body>
        <input type="text"
               value="Hello, World!"
               id="myInput">
        <button onclick="myFunction()">Copy text</button>

        <p>The document.execCommand() method is not supported
           in Internet&nbsp;Explorer&nbsp;8 and earlier.</p>

        <script>
            function myFunction() {
                var copyText = document.getElementById("myInput");
                copyText.select();
                document.execCommand("copy");
                alert("Copied the text: " + copyText.value);
            }
        </script>
    </body>
</html>

答案 48 :(得分:1)

简单,易于使用且不是过时的解决方案:

function copyToClipboard(elementIdToCopy, elementIdToNotifyOutcome) {
    const contentToCopy = document.getElementById(elementIdToCopy).innerHTML;
    const elementToNotifyOutcome = document.getElementById(elementIdToNotifyOutcome);

    navigator.clipboard.writeText(contentToCopy).then(function() {
        elementToNotifyOutcome.classList.add('success');
        elementToNotifyOutcome.innerHTML = 'Copied!';
    }, function() {
        elementToNotifyOutcome.classList.add('failure');
        elementToNotifyOutcome.innerHTML = 'Sorry, did not work.';
    });
}

答案 49 :(得分:1)

我在一个简单的解决方案中编译了一些功能,以涵盖所有情况,并在需要时立即回退。

window.copyToClipboard = function(text) {
  // IE specific
  if (window.clipboardData && window.clipboardData.setData) {
    return clipboardData.setData("Text", text);
  }

  // all other modern
  target = document.createElement("textarea");
  target.style.position = "absolute";
  target.style.left = "-9999px";
  target.style.top = "0";
  target.textContent = text;
  document.body.appendChild(target);
  target.focus();
  target.setSelectionRange(0, target.value.length);

  // copy the selection of fall back to prompt
  try {
    document.execCommand("copy");
    target.remove();
    console.log('Copied to clipboard: "'+text+'"');
  } catch(e) {
    console.log("Can't copy string on this browser. Try to use Chrome, Firefox or Opera.")
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
}

在此处测试https://jsfiddle.net/jv0avz65/

答案 50 :(得分:1)

这是唯一对我有用的东西:

{{1}}

答案 51 :(得分:1)

只是将我的答案添加到我的答案中。

这是最好的。如此多的胜利。

var toClipboard = function(text) {
        var doc = document;

        // Create temp element
        var textarea = doc.createElement('textarea');
        textarea.style.position = 'absolute';
        textarea.style.opacity  = '0';
        textarea.textContent    = text;

        doc.body.appendChild(textarea);

        textarea.focus();
        textarea.setSelectionRange(0, textarea.value.length);

        // copy the selection
        var success;
        try {
                success = doc.execCommand("copy");
        } catch(e) {
                success = false;
        }

        textarea.remove();

        return success;
}

答案 52 :(得分:0)

注意::不是this answer的副本,因为该库与该库完全无关,而该库更受欢迎。

Clipboard.js是一个受欢迎的库(在GitHub上为29.5k星,在npm上每周下载310万次,在jsDelivr上每月点击数为7.04亿次)使复制文本到剪贴板变得非常容易:

<script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script>

<!-- Target -->
<input id="foo" value="foo">

<!-- Trigger -->
<button class="btn" data-clipboard-target="#foo">
    <img src="assets/clippy.svg" alt="Copy to clipboard">
</button>

链接:

答案 53 :(得分:0)

以下功能可用于复制到电子白板

copyToclipboard = (event, text) => {
    var container = event.currentTarget;
    let tempInnerHtml = container.innerHTML;
    container.innerHTML = text;
    window.getSelection().removeAllRanges();
    let range = document.createRange();
    range.selectNode(container);
    window.getSelection().addRange(range);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    container.innerHTML = tempInnerHtml;
}

答案 54 :(得分:0)

这可以通过结合使用getElementbyId,Select(),blur()和复制命令来完成

注意

select()方法选择一个元素或具有文本字段的元素中的所有文本。这可能不适用于按钮

用法

let copyText = document.getElementById('input-field');
copyText.select()
document.execCommand("copy");
copyReferal.blur()
document.getElementbyId('help-text').textContent = 'Copied'

blur()方法将删除难看的突出显示部分,而不是您可以在优美的消息中看到您的内容已成功复制

答案 55 :(得分:0)

document.querySelector('#some_your_textfield_id').select();
document.execCommand('copy');

第一行以选择要复制的文本

第二行以复制所选文本

答案 56 :(得分:0)

function copytoclipboard(element) {


  var $temp = $("<input>");
        $("body").append($temp);
        $temp.val('0'+element).select();
        document.execCommand("copy");
        $temp.remove();

}

答案 57 :(得分:0)

我尝试了许多解决方案。如果它可以在现代浏览器中使用,它将无法在Internet Explorer中使用。如果它可以在Internet Explorer中运行,则无法在iOS上运行。我终于对它们进行了梳理,并得出以下修补程序,该修补程序可在所有浏览器,iOS,Webview和Android上使用。

注意:我还介绍了用户拒绝剪贴板权限的情况。此外,即使用户手动复制,也会显示“链接已复制”消息。

<div class="form-group col-md-12">
    <div class="input-group col-md-9">
        <input name="copyurl"
               type="text"
               class="form-control br-0 no-focus"
               id="invite-url"
               placeholder="http://www.invitelink.com/example"
               readonly>
        <span class="input-group-addon" id="copy-link" title="Click here to copy the invite link">
            <i class="fa fa-clone txt-18 text-success" aria-hidden="true"></i>
        </span>
    </div>
    <span class="text-success copy-success hidden">Link copied.</span>
</div>

脚本:

var addEvent =  window.attachEvent || window.addEventListener;
var event = 'copy';
var $inviteUrl = $('#invite-url');

$('#copy-link').on('click', function(e) {
    if ($inviteUrl.val()) {
        if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
            var el = $inviteUrl.get(0);
            var editable = el.contentEditable;
            var readOnly = el.readOnly;
            el.contentEditable = true;
            el.readOnly = false;
            var range = document.createRange();
            range.selectNodeContents(el);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
            el.setSelectionRange(0, 999999);
            el.contentEditable = editable;
            el.readOnly = readOnly;
            document.execCommand('copy');
            $inviteUrl.blur();
        }
        else {
            $inviteUrl.select();
            document.execCommand("copy");
        }
    }
});

addEvent(event, function(event) {
    if ($inviteUrl.val() && event.target.id == 'invite-url') {
        var $copyLink = $('#copy-link i');
        $copyLink.removeClass('fa-clone');
        $copyLink.addClass('fa-check');
        $('.copy-success').removeClass('hidden');
        setTimeout(function() {
            $copyLink.removeClass('fa-check');
            $copyLink.addClass('fa-clone');
            $('.copy-success').addClass('hidden');
        }, 2000);
    }
});

答案 58 :(得分:0)

使用document.execCommand将为您完成这项工作...

您还可以剪切复制粘贴 ...

这是一个简单的剪贴板复制功能,可复制输入文本中的所有内容...

function copyInputText() {
  var copyText = document.querySelector("#input");
  copyText.select();
  document.execCommand("copy");
}

document.querySelector("#copy").addEventListener("click", copyInputText);
<input id="input" type="text" />
<button id="copy">Copy</button>

有关更多信息,请访问here

答案 59 :(得分:0)

这是我的解决方案

var codeElement = document.getElementsByClassName("testelm") && document.getElementsByClassName("testelm").length ? document.getElementsByClassName("testelm")[0] : "";
        if (codeElement != "") {
            var e = document.createRange();
            e.selectNodeContents(codeElement);
            var selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(e);
            document.execCommand("Copy");
            selection.removeAllRanges();
        }

答案 60 :(得分:0)

我已将@ dean-taylor提供的解决方案与来自其他地方的其他一些select / unselect代码整合到NPM上提供的jQuery插件中:

https://www.npmjs.com/package/jquery.text-select

安装:

npm install --save jquery.text-select

用法:

<script>
    $(document).ready(function(){
        $("#selectMe").selectText(); // Hightlight / select the text
        $("#selectMe").selectText(false); // Clear the selection

        $("#copyMe").copyText(); // Copy text to clipboard
    });
</script>

有关方法/事件的更多信息可以在上面的NPM注册表页面找到。

答案 61 :(得分:-3)

这可能是您问题的解决方案

function CopyToNotepad(id){
    var r = document.createRange();
    r.selectNode(document.getElementById(id));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(r);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
}

注意:id 应该是您要将内容复制到的父元素 id。例如:假设您要复制列表中的所有内容,那么 id 应如下使用:

<ul id="dummy_id">
<li>copy content 1 </li>
<li>copy content 2 </li>
<li>copy content 3 </li>
<li>copy content 4 </li>
<li>copy content 5 </li>
</ul>

那么函数调用应该是这样的

CopyToNotepad(dummy_id)

谢谢。当然这可以解决您的问题!