我正在尝试将文本复制到 h3 标签内的剪贴板。我在 copyText.select() 代码行收到以下错误。
未捕获类型错误:copyText.select 不是函数 在 HTMLDivElement。
编辑:在输入标签上使用时,复制到剪贴板功能有效,但在 h3 标签内时无效。
HTML
<div class="colorDiv" id="firstColorObject">
<h3 class="colorCode" id="p1" value="123">#Color 1</h3>
</div>
JavaScript
document.querySelector("#firstColorObject").addEventListener("click", function(){
var copyText = document.getElementById("p1");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}, false);
最佳答案
您可以调用select用<input>
- 元素但不带 <h3>
-元素。
不过,您可以利用 <input>
当您分配 #p1
的内容时在调用 select
之前转到隐藏字段用它。
注意:调用select
仅当您将实际可见的字段包裹在 <div>
周围时,使用隐藏字段才有效- 隐藏的元素(仅使用 opacity:0
进行测试)。无法从像这样的真正隐藏的输入中复制值(通过 select
和 document.execCommand("copy")
):
<input type="hidden" id="copyText"/>
希望我下面的示例对您有所帮助(要执行它,请单击 "Run Code snippet"
- 按钮):
document.querySelector("#firstColorObject").addEventListener("click", function(){
var p1 = document.getElementById("p1");
// set "#Color 1" with the hidden field so that you can call select on it
var hiddenField = document.getElementById("copyText");
hiddenField.value = p1.innerHTML;
hiddenField.select();
document.execCommand("copy");
alert("Copied the text: " + hiddenField.value);
}, false);
<div class="colorDiv" id="firstColorObject">
<h3 class="colorCode" id="p1" value="123">#Color 1</h3>
<div style="opacity:0">
<input type="text" id="copyText"/>
</div>
</div>
关于javascript - 在 h3 标签内复制文本时,复制到剪贴板不是功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51544928/