如何将预标签代码复制到html中的剪贴板?

Suy*_*yog 3 html javascript clipboard

我正在尝试将pre标签内写的代码复制到剪贴板中.我怎样才能做到这一点?我试图使用下面的代码解决这个问题:

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
}
Run Code Online (Sandbox Code Playgroud)
<pre id="myInput">
    <span style="color:#97EDDC;">class </span>first
    {
    	<span style="color:#97EDDC;">public</span> <span style="color:#97EDDC;">static </span> <span style="color:#97EDDC;">void </span> main(String args[]) // here S is capital of String word
    	{
    		System.out.println("Hello World!!"); // here S is capital of System word
    	}
    }
</pre>
Run Code Online (Sandbox Code Playgroud)

给我一个正确的解决方案,将代码从pre标签复制到剪贴板,而不包括span标签.

Agn*_*ney 12

不幸的是,select()只能用于可见输入元素.所以你可以做的是提取pre元素的文本内容.

将此应用于textarea并将textarea放在普通视图区域之外.

function copyFunction() {
  const copyText = document.getElementById("myInput").textContent;
  const textArea = document.createElement('textarea');
  textArea.textContent = copyText;
  document.body.append(textArea);
  textArea.select();
  document.execCommand("copy");
}

document.getElementById('button').addEventListener('click', copyFunction);
Run Code Online (Sandbox Code Playgroud)
textarea {
  position: absolute;
  left: -100%;
}
 
            
Run Code Online (Sandbox Code Playgroud)
<pre id="myInput">
<span style="color:#97EDDC;">class </span>first
{
    <span style="color:#97EDDC;">public</span> <span style="color:#97EDDC;">static </span> <span style="color:#97EDDC;">void </span> main(String args[])
    {
        System.out.println("Hello World!!"); 
    }
}
            </pre>

<button id="button">Copy</button>
Run Code Online (Sandbox Code Playgroud)

  • 辉煌而简单。我建议在 `document.execCommand("copy");` : `textArea.remove();` 之后添加最新行,以将其从文档中删除...... (3认同)