簡體   English   中英

JavaScript如何復制到剪貼板?

[英]How do I copy to the clipboard in JavaScript?

如何將文本復制到剪貼板(多瀏覽器)?

相關: Trello 如何訪問用戶的剪貼板?

概述

有三個主要的瀏覽器 API 用於復制到剪貼板:

  1. 異步剪貼板 API [navigator.clipboard.writeText]

  2. document.execCommand('copy')已棄用)👎

    • 自 2015 年 4 月起,大多數瀏覽器都支持此功能(請參閱下面的瀏覽器支持)。
    • 訪問是同步的,即停止頁面中的 JavaScript 直到完成,包括顯示和用戶與任何安全提示進行交互。
    • 文本從 DOM 中讀取並放置在剪貼板上。
    • 在測試期間 ~ 2015 年 4 月,只有 Internet Explorer 被記錄為在寫入剪貼板時顯示權限提示。
  3. 覆蓋復制事件

    • 請參閱有關覆蓋復制事件的剪貼板 API 文檔。
    • 允許您從任何復制事件修改剪貼板上顯示的內容,可以包括純文本以外的其他格式的數據。
    • 這里沒有涉及,因為它沒有直接回答這個問題。

一般開發說明

當您在控制台中測試代碼時,不要期望剪貼板相關命令能夠正常工作。 通常,頁面需要處於活動狀態(異步剪貼板 API)或需要用戶交互(例如用戶單擊)以允許( document.execCommand('copy') )訪問剪貼板,請參閱下文了解更多詳細信息。

重要(此處注明 2020/02/20)

請注意,由於這篇文章最初是寫在跨域IFRAME 和其他IFRAME “沙盒”中的權限的棄用,因此會阻止嵌入式演示“運行代碼片段”按鈕和“codepen.io 示例”在某些瀏覽器中工作(包括 Chrome 和 Microsoft Edge )。

要開發創建您自己的網頁,請通過 HTTPS 連接提供該頁面以進行測試和開發。

這是一個演示代碼工作的測試/演示頁面: https ://deanmarktaylor.github.io/clipboard-test/

異步+后備

由於瀏覽器對新 Async Clipboard API 的支持程度,您可能希望回退到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-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>

(codepen.io 示例可能不起作用,請閱讀上面的“重要”注釋)請注意,此代碼段在 Stack Overflow 的嵌入式預覽中效果不佳,您可以在此處嘗試: https ://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors =1011

異步剪貼板 API

請注意,通過 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('復制')

本文的其余部分將介紹document.execCommand('copy') API 的細微差別和細節。

瀏覽器支持

JavaScript document.execCommand('copy')支持已增加,請參閱以下鏈接了解瀏覽器更新: 已棄用)👎

簡單示例

(可能無法嵌入本網站,請閱讀上面的“重要”說明)

 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'); } });
 <p> <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button> <textarea class="js-copytextarea">Hello I'm some text</textarea> </p>

復雜示例:復制到剪貼板而不顯示輸入

如果屏幕上有一個textareainput元素可見,上面的簡單示例效果很好。

在某些情況下,您可能希望將文本復制到剪貼板而不顯示input / textarea元素。 這是解決此問題的方法的一個示例(基本上是插入元素,復制到剪貼板,刪除元素):

使用 Google Chrome 44、Firefox 42.0a1 和 Internet Explorer 11.0.8600.17814 進行測試。

(可能無法嵌入本網站,請閱讀上面的“重要”說明)

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

補充說明

僅當用戶采取行動時才有效

所有document.execCommand('copy')調用必須作為用戶操作的直接結果進行,例如單擊事件處理程序。 這是一種防止在用戶不期望的情況下弄亂用戶剪貼板的措施。

有關詳細信息,請參閱此處的 Google Developers 帖子

剪貼板 API

注意完整的剪貼板 API 草案規范可以在這里找到: https ://w3c.github.io/clipboard-apis/

是否支持?

  • 如果命令“瀏覽器支持”,則document.queryCommandSupported('copy')應該返回true
  • 如果現在調用document.execCommand('copy')將成功,則document.queryCommandEnabled('copy')返回true 檢查以確保從用戶啟動的線程調用命令並滿足其他要求。

但是,作為瀏覽器兼容性問題的一個示例,如果命令是從用戶啟動的線程調用的,則從 2015 年 4 月到 2015 年 10 月的 Google Chrome 僅從document.queryCommandSupported('copy')返回true

請注意下面的兼容性詳細信息。

瀏覽器兼容性詳情

雖然對document.execCommand('copy')的簡單調用包含在由於用戶單擊而調用的try / catch塊中,這將為您提供最大的兼容性,但使用以下有一些附帶條件:

document.execCommanddocument.queryCommandSupporteddocument.queryCommandEnabled的任何調用都應包含在try / catch塊中。

不同的瀏覽器實現和瀏覽器版本在調用而不是返回false時會拋出不同類型的異常。

不同的瀏覽器實現仍在不斷變化,剪貼板 API仍在草稿中,因此請記住進行測試。

自動復制到剪貼板可能很危險,因此大多數瀏覽器(Internet Explorer 除外)都使其變得非常困難。 就個人而言,我使用以下簡單技巧:

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

向用戶呈現提示框,其中已選擇要復制的文本。 現在按下Ctrl + CEnter (關閉框)就足夠了——瞧!

現在剪貼板復制操作是安全的,因為用戶手動進行(但以一種非常簡單的方式)。 當然,它適用於所有瀏覽器。

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

以下方法適用於 Chrome、Firefox、Internet Explorer 和 Edge,以及最新版本的 Safari(2016 年 10 月發布的版本 10 中添加了復制支持)。

  • 創建一個 textarea 並將其內容設置為要復制到剪貼板的文本。
  • 將文本區域附加到 DOM。
  • 選擇文本區域中的文本。
  • 調用 document.execCommand("copy")
  • 從 dom 中刪除 textarea。

注意:您不會看到 textarea,因為它是在 Javascript 代碼的同一個同步調用中添加和刪除的。

如果您自己實現此功能,請注意以下幾點:

  • 出於安全原因,這只能從諸如 click 之類的事件處理程序中調用(就像打開窗口一樣)。
  • Internet Explorer 將在第一次更新剪貼板時顯示權限對話框。
  • Internet Explorer 和 Edge 將在 textarea 獲得焦點時滾動。
  • execCommand() 在某些情況下可能會拋出。
  • 除非您使用 textarea,否則換行符和制表符可能會被吞下。 (大多數文章似乎都建議使用 div)
  • 當 Internet Explorer 對話框顯示時,textarea 將可見,您要么需要隱藏它,要么使用 Internet Explorer 特定的 clipboardData API。
  • 在 Internet Explorer 中,系統管理員可以禁用剪貼板 API。

下面的函數應該盡可能干凈地處理以下所有問題。 如果您發現任何問題或有任何改進建議,請發表評論。

// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
// Internet Explorer: The clipboard feature may be disabled by
// an administrator. By default a prompt is shown the first
// time the clipboard is used (per session).
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
        return window.clipboardData.setData("Text", text);

    }
    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        }
        catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return prompt("Copy to clipboard: Ctrl+C, Enter", text);
        }
        finally {
            document.body.removeChild(textarea);
        }
    }
}

https://jsfiddle.net/fx6a6n6x/

這是我對那個的看法...

function copy(text) {
    var input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    var result = document.execCommand('copy');
    document.body.removeChild(input);
    return result;
 }

@korayem:請注意,使用 html input字段不會尊重換行符\n並將任何文本展平為一行。

正如@nikksan 在評論中提到的那樣,使用textarea將解決以下問題:

function copy(text) {
    var input = document.createElement('textarea');
    input.innerHTML = text;
    document.body.appendChild(input);
    input.select();
    var result = document.execCommand('copy');
    document.body.removeChild(input);
    return result;
}

從網頁讀取和修改剪貼板會引發安全和隱私問題。 但是,在 Internet Explorer 中,可以這樣做。 我找到了這個示例片段

 <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 分鍾)並且開箱即用看起來不錯,那么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}替換為顏色。

我最近寫了一篇關於這個問題的技術博客文章(我在 Lucidchart 工作,我們最近對剪貼板進行了大修)。

將純文本復制到剪貼板相對簡單,假設您嘗試在系統復制事件期間執行此操作(用戶按Ctrl + C或使用瀏覽器的菜單)。

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 進行操作的方法,這是唯一的跨瀏覽器方法(據我所知)。

除此之外,還有一些基於瀏覽器的選項。

這是 Internet Explorer 中最簡單的方法,您可以隨時通過 JavaScript 訪問 clipboardData 對象:

window.clipboardData

(但是,當您嘗試在系統剪切、復制或粘貼事件之外執行此操作時,Internet Explorer 將提示用戶授予 Web 應用程序剪貼板權限。)

在 Chrome 中,您可以創建一個 Chrome 擴展程序,該擴展程序將為您提供剪貼板權限(這是我們為 Lucidchart 所做的)。 然后對於安裝了您的擴展程序的用戶,您只需要自己觸發系統事件:

document.execCommand('copy');

看起來 Firefox 有一些選項允許用戶授予某些網站訪問剪貼板的權限,但我個人沒有嘗試過這些。

我喜歡這個:

<input onclick="this.select();" type='text' value='copy me' />

如果用戶不知道如何在他們的操作系統中復制文本,那么他們很可能也不知道如何粘貼。 因此,只需自動選擇它,其余的留給用戶。

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 上

注意:現在已棄用。 遷移到這里

在 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。

剪貼板的東西也可以做更多的體操。 在此處查看更多信息:

取消阻止剪貼板訪問

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

function copyToClp(txt){
    var m = document;
    txt = m.createTextNode(txt);
    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 中)。

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

由於 Chrome 42+ 和 Firefox 41+ 現在支持document.execCommand('copy')命令,因此我結合使用Tim Down 的舊答案Google Developer 的答案,創建了幾個用於跨瀏覽器復制到剪貼板功能的函數:

 function selectElementContents(el) { // Copy textarea, pre, div, etc. if (document.body.createTextRange) { // Internet Explorer var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.select(); textRange.execCommand("Copy"); } else if (window.getSelection && document.createRange) { // Non-Internet Explorer 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 Internet Explorer 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>

 $("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

在我從事的一個項目中,一個利用ZeroClipboard庫的 jQuery 復制到剪貼板插件。

如果你是一個重度 jQuery 用戶,它比原生的 Zero Clipboard 插件更容易使用。

我找到了以下解決方案:

on-key-down 處理程序創建一個“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 did 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('Failed to paste. :(');
    };
}

用法:

enyby_clip = new EnybyClipboard(); // Init

enyby_clip.copyText('some_text'); // Place this in the 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;

在粘貼時,它會創建一個文本區域並以相同的方式工作。

PS:也許這個解決方案可以用來創建一個沒有 Flash 的完整的跨瀏覽器解決方案。 它適用於 Firefox 和 Chrome。

我把我認為最好的一個放在一起。

  • 使用 cssText 來避免 Internet Explorer 中的異常,而不是直接使用樣式。
  • 如果有選擇,則恢復選擇
  • 設置為只讀,這樣鍵盤就不會出現在移動設備上
  • 有一個適用於 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 programmatic 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) {
      console.error(err);
      return false;
    }
  };
})();

用法: copyToClipboard('some text')

其他方法會將純文本復制到剪貼板。 要復制 HTML(即,您可以將結果粘貼到所見即所得的編輯器中),您只能在 Internet Explorer 中執行以下操作。 這與其他方法根本不同,因為瀏覽器實際上是在可見地選擇內容。

// 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();

JavaScript/TypeScript 中最好和最簡單的方法使用這個命令

navigator.clipboard.writeText(textExample);

只需在textExample中傳遞您想要復制到剪貼板的值

此代碼在 2021 年 5 月測試。 在 Chrome、IE、Edge 上工作。 下面的“消息”參數是您要復制的字符串值。

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

從 Flash 10 開始,如果操作源自用戶與 Flash 對象的交互,則只能復制到剪貼板。 閱讀 Adob​​e 的 Flash 10 公告中的相關部分。)

解決方案是在 Copy 按鈕或啟動復制的任何元素上方覆蓋 Flash 對象。 ZeroClipboard 是目前具有此實現的最佳庫。 經驗豐富的 Flash 開發人員可能只想制作自己的庫。

已經有很多答案,但是想添加一個(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.');
}

我找到了以下解決方案:

我在隱藏輸入中有文本。 因為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;
}

將文本復制到剪貼板(多瀏覽器)的最佳方法是什么?

我試過了:

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未定義

不使用Flash的一個不錯的技巧: Trello如何訪問用戶的剪貼板?

將文本從 HTML 輸入復制到剪貼板:

 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); }
 <!-- The text field --> <input type="text" value="Hello Friend" id="myInput"> <!-- The button used to copy the text --> <button onclick="myFunction()">Copy text</button>

注意: Internet Explorer 9 和更早版本不支持document.execCommand()方法。

來源W3Schools -將文本復制到剪貼板

復制文本字段內文本的最佳方法。 使用navigator.clipboard.writeText

<input type="text" value="Hello World" id="myId">
<button onclick="myFunction()" >Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);
}

</script>

這是其他答案之間的一些組合。

var copyToClipboard = function(textToCopy){
    $("body")
        .append($('<textarea 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($('<textarea name="fname" style="opacity: 0;  position: absolute;" class="textToCopyInput"/>' )

在 Internet Explorer 以外的瀏覽器中,您需要使用一個小的 Flash 對象來操作剪貼板,例如

從(類似於 Excel)構建自定義網格編輯以及與 Excel 的兼容性時,我遇到了同樣的問題。 我必須支持選擇多個單元格、復制和粘貼。

解決方案:創建一個文本區域,您將在其中插入數據供用戶復制(對於我來說,當用戶選擇單元格時),將焦點設置在它上面(例如,當用戶按下Ctrl時)並選擇整個文本。

因此,當用戶按 Ctrl + C時,他/她會復制他/她選擇的單元格。 測試后,只需將 textarea 的大小調整為一個像素(我沒有測試它是否可以在 display:none 上工作)。 它適用於所有瀏覽器,並且對用戶透明。

粘貼 - 你可以這樣做(在你的目標上有所不同) - 繼續關注 textarea 並使用 onpaste 捕獲粘貼事件(在我的項目中,我在單元格中使用 textareas 進行編輯)。

我無法粘貼示例(商業項目),但您明白了。

function copytoclipboard(element) {

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

Stackoverflow 的解決方案

我只是想指出 Stackoverflow 實際上就是這樣做的。 在每個答案下都有一個“共享”鏈接 - 當您單擊該鏈接時,它會打開一個彈出窗口,其中在輸入中突出顯示共享鏈接,以及一個“復制鏈接”鏈接:

在此處輸入圖像描述

如果你去 Chrome DevTools 並去那個鏈接的事件監聽器,你可以找到他們使用的函數。 它被稱為 tryCopy():

在此處輸入圖像描述

這與Dean Taylors 在這里的回答(最近更新)完全一致 - 具體閱讀標題為"Async + Fallback"的部分。 TL;DR 是:嘗試使用navigator.clipboard api - 如果瀏覽器不支持,請回退到 document.execCommand()。

我用過剪貼板.js。

我們可以在 npm 上獲取它:

npm install clipboard --save

還有在鮑爾

bower install clipboard --save

 new ClipboardJS("#btn1"); document.querySelector("#btn2").addEventListener("click", () => document.querySelector("#btn1").dataset.clipboardText = Math.random());
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js"></script> <button id="btn1" data-clipboard-text="Text to copy goes here"> Copy to clipboard </button> <button id="btn2">Click here to change data-clipboard-text</button> <br /><br /> <input type="text" placeholder="Paste here to see clipboard" />

更多用法和示例位於https://zenorocha.github.io/clipboard.js/

要將選定的文本(“要復制的文本”)復制到剪貼板,請創建一個 Bookmarklet(執行 JavaScript 的瀏覽器書簽)並執行它(單擊它)。 它將創建一個臨時文本區域。

來自 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');

嘗試使用此功能


const copyToClipboard = (
  value,
  successfully = () => null,
  failure = () => null
) => {
  const clipboard = navigator.clipboard;
  if (clipboard !== undefined && clipboard !== "undefined") {
    navigator.clipboard.writeText(value).then(successfully, failure);
  } else {
    if (document.execCommand) {
      const el = document.createElement("input");
      el.value = value;
      document.body.append(el);

      el.select();
      el.setSelectionRange(0, value.length);

      if (document.execCommand("copy")) {
        successfully();
      }

      el.remove();
    } else {
      failure();
    }
  }
};

這是Chase Seibert 答案的擴展,其優點是它適用於 IMAGE 和 TABLE 元素,而不僅僅是 Internet Explorer 9 上的 DIV。

if (document.createRange) {
    // Internet Explorer 9 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 Firefox
} else {
    // Internet Explorer 8 and earlier. This stuff won't work
    // on Internet Explorer 9.
    // (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');
}

這可以立即使用,使用最新的Clipboard API和用戶交互:

 copy.addEventListener("pointerdown", () => navigator.clipboard.writeText("Hello World!"))
 <button id="copy">Copy Hello World!</button>

我的錯。 這僅適用於 Internet Explorer。

這是另一種復制文本的方法:

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

這是我在互聯網上查找各種方法后唯一開始工作的事情。 這是一個混亂的話題。 世界各地發布了許多解決方案,但其中大多數都不起作用 這對我有用:

注意:此代碼僅在作為類似“onClick”方法的直接同步代碼執行時才有效。 如果您調用對 Ajax 的異步響應或以任何其他異步方式,它將不起作用。

copyToClipboard(text) {
    var copyText = document.createElement("input");
    copyText.type = "text";
    document.body.appendChild(copyText);
    copyText.style = "display: inline; width: 1px;";
    copyText.value = text;
    copyText.focus();
    document.execCommand("SelectAll");
    document.execCommand("Copy");
    copyText.remove();
}

我確實意識到這段代碼會在屏幕上顯示一個 1 像素寬的組件,持續一毫秒,但我決定不用擔心,如果真的有問題,其他人可以解決這個問題。

似乎我誤讀了這個問題,但作為參考,您可以提取 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 it 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;
  }
}

我不願意對此添加另一個答案,但為了幫助像我這樣的菜鳥,因為這是谷歌的最高結果,我會的。

在 2022 年將文本復制到剪貼板您使用一行

navigator.clipboard.writeText(textToCopy);

這將返回一個 Promise,如果復制則解決,如果失敗則拒絕。

一個完整的工作 function 是這樣的:

async function copyTextToClipboard(textToCopy) {
    try {
        await navigator.clipboard.writeText(textToCopy);
        console.log('copied to clipboard')
    } catch (error) {
        console.log('failed to copy to clipboard. error=' + error);
    }
}

警告! 如果您在測試時打開了 Chrome 開發工具,它將失敗,因為瀏覽器要啟用剪貼板,它需要您聚焦 window。 這是為了防止隨機網站在您不想要的情況下更改您的剪貼板。 Dev Tools 竊取了這個焦點,所以關閉 Dev Tools 並且您的測試將起作用。

如果您想將其他內容(圖像等)復制到剪貼板,請查看這些文檔。

https://developer.mozilla.org/zh-CN/docs/Web/API/Clipboard_API

這在瀏覽器中得到了足夠的支持,您可以使用它。 如果您擔心 Firefox,請在瀏覽器支持的情況下使用權限查詢來顯示或隱藏該按鈕。 https://developer.mozilla.org/zh-CN/docs/Web/API/Permissions/query

據我所知,這只適用於 Internet Explorer。

另請參閱Dynamic Tools - JavaScript Copy To Clipboard ,但它需要用戶先更改配置,即使那樣它似乎也不起作用。

看起來您從Greasemonkey\JavaScript 復制到剪貼板按鈕或此代碼段的原始來源中獲取了代碼...

此代碼用於 Greasemonkey,因此是 unsafeWindow。 而且我猜 Internet Explorer 中的語法錯誤來自const特定於 Firefox 的關鍵字(將其替換為var )。

這是同一網站的簡單的基於 Ajax/會話的剪貼板。

請注意,會話必須啟用且有效,並且此解決方案適用於同一站點。 我在 CodeIgniter 上對其進行了測試,但遇到了 session/Ajax 問題, 但這也解決了這個問題。 如果您不想玩會話,請使用數據庫表。

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

我不得不從頁面中復制非輸入框文本(任何 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 中添加以下內容:

input type="text" id="hiddenField" style="width:5px;border:0" />
...

如果復制的鏈接必須粘貼在同一個站點上,那么一個簡單的解決方案是在按下簡單的 HTML 復制按鈕之前突出顯示文本,然后按下它,文本內容將存儲在會話中。 在要粘貼的地方,都有一個粘貼按鈕。

**我知道,這不是一個持久和通用的解決方案,但它是 :)

如果您在 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;
}

除了Dean Taylor 的更新答案(2015 年 7 月) ,我還寫了一個 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();
    }
};

2015 年更新:目前有一種方法可以使用document.execCommand來處理剪貼板。

clipboard.js提供了一種使用剪貼板的跨瀏覽器方式(瀏覽器支持)。

這里找到了這個解決方案。 document.execCommand("copy"); Internet Explorer 8 及更早版本不支持。

 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>

簡單、即用型且不會過時的解決方案:

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

在 Chrome 中,您可以使用copy('the text or variable etc') 雖然這不是跨瀏覽器(並且不能在片段中工作? ),但您可以將其添加到其他跨瀏覽器答案中。

我打算使用clipboard.js,但它沒有任何移動解決方案(還)......所以我寫了一個超級小庫:

雪佛蘭

這將復制文本(桌面、Android 和 Safari 10+),或者至少選擇文本(舊版本的 iOS)。 縮小它剛剛超過 1 kB。 在桌面 Safari(版本 10 之前)中,它告訴用戶"Press Command + C to copy" 您也無需編寫任何 JavaScript 即可使用它。

我在一個簡單的解決方案中編譯了一些函數來涵蓋所有情況,如果需要,可以及時回退。

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

  // All other modern browsers
  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/

這是唯一對我有用的東西:

let textarea = document.createElement('textarea');
textarea.setAttribute('type', 'hidden');
textarea.textContent = 'the string you want to copy';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');

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

使用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>

有關詳細信息,請參閱與剪貼板交互(附加組件)。

這是一個獨立的類,通過將其放置在屏幕外來確保臨時textarea不會發生閃爍。

這適用於 Safari(桌面)、Firefox 和 Chrome。

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

    function copyText(text) {
        // Create a temporary 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
    };

})();

以下函數可用於復制到剪貼板:

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

添加到 Dean Taylor 的答案,這里有一個簡短的答案和一個長答案,因此您可以復制適合您需要的功能:

簡短的回答:

只需使用navigator.clipboard.writeText(str)

請參閱caniuse.com 上的剪貼板 API

長答案:

    // Copies a string to clipboard
    // Uses navigator API if available, else uses execCommand (deprecated)
    // Returns a boolean if copy was successful
    // See: https://stackoverflow.com/q/400212/4907950
        async function copyText(str) {
        console.log('Copying', str);
        if (!navigator.clipboard) {
            // fallback
            let input = document.createElement('textarea');
            input.innerHTML = str;
            document.body.appendChild(input);
            input.focus();
            input.select();
            let result;

            try {
                result = document.execCommand('copy');
                console.log(
                    'Fallback: Copying text command was ' + (result ? 'successful' : 'unsuccessful')
                );
            } catch (err) {
                console.error('Fallback: Could not copy text: ', err);
            }
            document.body.removeChild(input);
            return result;
        }
        const result = navigator.clipboard.writeText(str).then(
            function () {
                console.log('Async: Copying to clipboard was successful');
                return true;
            },
            function (err) {
                console.error('Async: Could not copy text: ', err);
                return false;
            }
        );
        return result;

嘗試使用這個:

<a href="#" onclick="copyToClipboard('what the foo')">click</a>

<script>
function copyToClipboard(value) {
  navigator.clipboard.writeText(value)
}
</script>

出於安全原因,您不能這樣做。 您必須選擇 Flash 才能復制到剪貼板。

我建議這個:http: //zeroclipboard.org/

搜索支持 Safari 和其他瀏覽器(Internet Explorer 9 及更高版本)的解決方案后,

我使用和 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>

JavaScript

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

這是最好的。 贏了這么多。

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

    // Create temporary 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;
}

這是一個簡單的例子;)

<!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>
document.querySelector('#some_your_textfield_id').select();
document.execCommand('copy');

第一行是選擇要復制的文本。

第二行是復制選定的文本。

這是我發現的最簡單的方法

<!DOCTYPE html>
<html>
<body>

 <p>Click on the button to copy the text from the text field. Try to paste 
 the text (e.g. ctrl+v) afterwards in a different window, to see the effect. 
 </p>

  <input type="text" value="Hello World" id="myInput">
  <button onclick="myFunction()">Copy text</button>

  <script>
 function myFunction() {
   /* Get the text field */
   var copyText = document.getElementById("myInput");

  /* Select the text field */
   copyText.select();
    copyText.setSelectionRange(0, 99999); /* For mobile devices */

   /* Copy the text inside the text field */
   navigator.clipboard.writeText(copyText.value);

   /* Alert the copied text */
    alert("Copied the text: " + copyText.value);
    }

   </script>

    </body>
    </html>

此代碼修復了兼容性問題、權限未授予問題、異步問題和 Apple Safari 問題,這些問題無法與writeText正常工作我在最近的 stackoverflow 帖子中描述了所有這些問題。

function copy(text) {
    return new Promise((resolve, reject) => {
        if (typeof navigator !== "undefined" && typeof navigator.clipboard !== "undefined" && navigator.permissions !== "undefined") {
            const type = "text/plain";
            const blob = new Blob([text], { type });
            const data = [new ClipboardItem({ [type]: blob })];
            navigator.permissions.query({name: "clipboard-write"}).then((permission) => {
                if (permission.state === "granted" || permission.state === "prompt") {
                    navigator.clipboard.write(data).then(resolve, reject).catch(reject);
                }
                else {
                    reject(new Error("Permission not granted!"));
                }
            });
        }
        else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
            var textarea = document.createElement("textarea");
            textarea.textContent = text;
            textarea.style.position = "fixed";
            textarea.style.width = '2em';
            textarea.style.height = '2em';
            textarea.style.padding = 0;
            textarea.style.border = 'none';
            textarea.style.outline = 'none';
            textarea.style.boxShadow = 'none';
            textarea.style.background = 'transparent';
            document.body.appendChild(textarea);
            textarea.focus();
            textarea.select();
            try {
                document.execCommand("copy");
                document.body.removeChild(textarea);
                resolve();
            }
            catch (e) {
                document.body.removeChild(textarea);
                reject(e);
            }
        }
        else {
            reject(new Error("None of copying methods are supported by this browser!"));
        }
    });
    
}

用法

try {
    await copy("Hay yah!");
}
catch(e) {
    console.error(e);
}

重要說明:通過按鈕和 onclick 事件測試它,而不是在控制台中。

我已經將@dean-taylor 提出的解決方案與其他地方的一些其他選擇/取消選擇代碼一起放在 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 注冊表頁面中找到。

這是 Angular 5.x+ 的優雅解決方案:

零件:

import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnInit,
  Output,
  Renderer2,
  ViewChild
} from '@angular/core';

@Component({
  selector: 'copy-to-clipboard',
  templateUrl: './copy-to-clipboard.component.html',
  styleUrls: ['./copy-to-clipboard.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class CopyToClipboardComponent implements OnInit {
  @ViewChild('input') input: ElementRef;
  @Input() size = 'md';
  @Input() theme = 'complement';
  @Input() content: string;
  @Output() copied: EventEmitter<string> = new EventEmitter<string>();
  @Output() error: EventEmitter<string> = new EventEmitter<string>();

  constructor(private renderer: Renderer2) {}

  ngOnInit() {}

  copyToClipboard() {

    const rootElement = this.renderer.selectRootElement(this.input.nativeElement);

    // 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)) {

      this.renderer.setAttribute(this.input.nativeElement, 'contentEditable', 'true');

      const range = document.createRange();

      range.selectNodeContents(this.input.nativeElement);

      const sel = window.getSelection();

      sel.removeAllRanges();
      sel.addRange(range);

      rootElement.setSelectionRange(0, 999999);
    } else {
      rootElement.select();
    }

    try {
      document.execCommand('copy');
      this.copied.emit();
    } catch (err) {
      this.error.emit(err);
    }
  };
}

模板:

<button class="btn btn-{{size}} btn-{{theme}}" type="button" (click)="copyToClipboard()">
  <ng-content></ng-content>
</button>

<input #input class="hidden-input" [ngModel]="content">

款式:

.hidden-input {
  position: fixed;
  top: 0;
  left: 0;
  width: 1px; 
  height: 1px;
  padding: 0;
  border: 0;
  box-shadow: none;
  outline: none;
  background: transparent;
}

這是我的解決方案:

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

可以通過使用 getElementbyId、Select()、blur() 和復制命令的組合來完成。

筆記

select() 方法選擇 <textarea> 元素或帶有文本字段的 <input> 元素中的所有文本。 這可能不適用於按鈕。

用法

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

blur() 方法將刪除難看的突出顯示部分,而不是您可以在漂亮的消息中顯示您的內容已成功復制

我嘗試了很多解決方案。 如果它適用於現代瀏覽器,則它不適用於 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);
    }
});

這是我根據每個人的答案對答案的看法。 請注意,此答案考慮了幾件事:

  1. 確保navigator.clipboard.writeText()是復制的主要方式
  2. 確保使用現代 JS 正確解析writeText() promise - 根據 2022 年。

 async function copyText(e) { const elem = e.currentTarget; const text = elem.textContent; try { await navigator.clipboard.writeText(text); elem.textContent = "Copied to Clipboard;". } catch (err) { //use document.execCommand('copy') as fallback const textArea = document;createElement("textarea"). textArea;value = text. document.body;appendChild(textArea). textArea;focus(). textArea;select(). document;execCommand("copy"). elem;textContent = "Copied to Clipboard.". document;body.removeChild(textArea); } finally { setTimeout(() => { elem,textContent = text; }. 2000). } } document.querySelector(",target-elem-whatever");addEventListener("click", copyText);
 <button class="target-elem-whatever">This text should be inside your clipboard.</button>

這很簡單。 您可以將導航器與 function 一起使用。之后,這只是您要如何復制指定文本的問題。 我通常這樣做:

<div id="mybox">Hello World</div>

<script>
const _ = (id) => { return document.getElementById(id) }

const copy = (text) => { 
  navigator.clipboard.writeText(text)
  alert('Copied to clipboard');
}

_('mybox').addEventListener('click', () => {
   let text = _('mybox').innerText;
   copy(text);
});
</script>

試試這個

簡單復制JS

Copy text function copyfunction() { // 獲取文本字段 var copyText = document.getElementById("text_to_copy"); navigator.clipboard.writeText(copyText.innerText).then( () => { alert("copied"); }, () => { alert("not copied"); } ); }

對我來說少即是多

const text = "Copy me please!";
navigator.clipboard.writeText(text);

都好。

這可能是您問題的解決方案

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)

謝謝。 當然這可以解決你的問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM