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

问题描述 投票:3回答:1

这个问题在这里已有答案:

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

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
}
<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>

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

javascript html clipboard
1个回答
9
投票

不幸的是,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);
textarea {
  position: absolute;
  left: -100%;
}
 
            
<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>
© www.soinside.com 2019 - 2024. All rights reserved.