如何将 <pre> 标签代码复制到 HTML 中的剪贴板?
How can I copy <pre> tag code into clipboard in HTML?
我正在尝试将写在 <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 标签。
不幸的是,select()
只能用于可见的输入元素。
所以你可以做的是提取 pre
元素的文本内容。
将此应用于文本区域并将文本区域定位在正常视图区域之外。
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>
我正在尝试将写在 <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 标签。
不幸的是,select()
只能用于可见的输入元素。
所以你可以做的是提取 pre
元素的文本内容。
将此应用于文本区域并将文本区域定位在正常视图区域之外。
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>