如何将文本从div复制到剪贴板

Ale*_*lex 35 javascript jquery

以下是用户点击此按钮时的代码:

<button id="button1">Click to copy</button>
Run Code Online (Sandbox Code Playgroud)

如何复制此div中的文本?

<div id="div1">Text To Copy</div>
Run Code Online (Sandbox Code Playgroud)

Eld*_*Age 56

两者都会像魅力:),

  1. JAVASCRIPT:

    function CopyToClipboard(containerid) {
    if (document.selection) { 
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy"); 
    
    } else if (window.getSelection) {
        var range = document.createRange();
         range.selectNode(document.getElementById(containerid));
         window.getSelection().addRange(range);
         document.execCommand("copy");
         alert("text copied") 
    }}
    
    Run Code Online (Sandbox Code Playgroud)

也在html中,

<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

<div id="div1" >Text To Copy </div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
Run Code Online (Sandbox Code Playgroud)

这是片段.

function CopyToClipboard(containerid) {
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select().createTextRange();
    document.execCommand("copy");

  } else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(document.getElementById(containerid));
    window.getSelection().addRange(range);
    document.execCommand("copy");
    alert("text copied, copy in the text-area")
  }
}
Run Code Online (Sandbox Code Playgroud)
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

<div id="div1">Text To Copy </div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
Run Code Online (Sandbox Code Playgroud)

  • 只是添加到这个答案,有一个整洁的插件,我已经使用了几次可以处理这个:https://clipboardjs.com/ (7认同)
  • 第一个不工作 (6认同)
  • 在调用 window.getSelection().addRange(range) 之前,调用此方法 window.getSelection().removeAllRanges() (4认同)
  • 请告诉我第一个例子如何工作 (2认同)
  • 我有一个问题,这将在所有浏览器上工作吗? (2认同)
  • 我希望它能做到.检查firefox和chrome. (2认同)

J. *_*cía 38

我尝试了上面提出的解决方案.但它不够跨浏览器.我真的需要ie11才能工作.尝试后我得到:

    <html>
        <body>
            <div id="a" onclick="copyDivToClipboard()"> Click to copy </div>
            <script>
                function copyDivToClipboard() {
                    var range = document.createRange();
                    range.selectNode(document.getElementById("a"));
                    window.getSelection().removeAllRanges(); // clear current selection
                    window.getSelection().addRange(range); // to select text
                    document.execCommand("copy");
                    window.getSelection().removeAllRanges();// to deselect
                }
            </script>
        </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

使用firefox 64,Chrome 71,Opera 57,ie11(11.472.17134.0),edge(EdgeHTML 17.17134)进行测试

更新2019年1月4日.

出于某种原因,document.createRange()在使用ie11之前没有工作.但现在正确返回Range对象.所以最好使用它,而不是document.getSelection().getRangeAt(0).

  • 这应该是该线程中的最佳答案。在找到一个可行的解决方案几个小时后,这终于对我有用。谢谢。:-) (2认同)

rom*_*n21 11

当您要复制多个项目,并且每个项目都有一个单独的“复制到剪贴板”按钮时,接受的答案将不起作用。单击一个按钮后,其他按钮将不起作用。

为了使它们起作用,我在接受答案的功能中添加了一些代码,以在执行新选择之前清除文本选择:

function CopyToClipboard(containerid) {
    if (window.getSelection) {
        if (window.getSelection().empty) { // Chrome
            window.getSelection().empty();
        } else if (window.getSelection().removeAllRanges) { // Firefox
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) { // IE?
        document.selection.empty();
    }

    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select().createTextRange();
        document.execCommand("copy");
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().addRange(range);
        document.execCommand("copy");
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

我得到 selectNode() param 1 is not type node error。

将代码更改为此及其工作。(镀铬)

function copy_data(containerid) {
  var range = document.createRange();
  range.selectNode(containerid); //changed here
  window.getSelection().removeAllRanges(); 
  window.getSelection().addRange(range); 
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
  alert("data copied");
}
Run Code Online (Sandbox Code Playgroud)
<div id="select_txt">This will be copied to clipboard!</div>
<button type="button" onclick="copy_data(select_txt)">copy</button>
<br>
<hr>
<p>Try paste it here after copying</p>
<textarea></textarea>
Run Code Online (Sandbox Code Playgroud)


lor*_*isi 5

此解决方案在复制到剪贴板后添加取消选择文本:

function copyDivToClipboard(elem) {
    var range = document.createRange();
    range.selectNode(document.getElementById(elem));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
}
Run Code Online (Sandbox Code Playgroud)


Oso*_*IAM 5

<div id='myInputF2'> YES ITS DIV TEXT TO COPY  </div>

<script>

    function myFunctionF2()  {
        str = document.getElementById('myInputF2').innerHTML;
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        alert('Copied the text:' + el.value);
    };
</script>
Run Code Online (Sandbox Code Playgroud)

更多信息:https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f


And*_*ich 5

在这里您可以看到适用于不同浏览器(包括 iOS)的代码。

const copyToClipboard = (id) => {
  var r = document.createRange();
  r.selectNode(document.getElementById(id));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(r);
  document.execCommand("copy");
  window.getSelection().removeAllRanges();
};

const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;

const copyIOS = (id) => {
  const text = document.getElementById(id).innerHTML;

  if (!navigator.clipboard) {
    const textarea = document.createElement("textarea");

    textarea.value = text;
    textarea.style.fontSize = "20px";
    document.body.appendChild(textarea);

    const range = document.createRange();
    range.selectNodeContents(textarea);

    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    textarea.setSelectionRange(0, 999999);

    document.execCommand("copy");

    document.body.removeChild(textarea);
  }

  navigator.clipboard.writeText(text);
};

const copyTextById = (id) => {
  if (isIOS) {
    return copyIOS(id);
  }
  copyToClipboard(id);
};

window.copyTextById = copyTextById
Run Code Online (Sandbox Code Playgroud)
<div id="text">Text which you will copy</div>

<button onclick="copyTextById('text')">Click me</button>
Run Code Online (Sandbox Code Playgroud)