如何选择要复制的变量


var delayBecauseFirebase = 1000;
setTimeout(function() {
var buttonShowJ = document.getElementById("buttonShow");
var messagesInJ = document.getElementById("messagesIn");
if(buttonShowJ)
{
buttonShowJ.addEventListener("click",function(){
var info = messagesInJ.innerHTML.replace(`<button id="buttonShow">Copy</button>`,"");
info.select(); \**(!HERE, because that doesnt works)**
document.execCommand("copy");
});
}else{
console.log("error");
}
}, delayBecauseFirebase);

我想选择";文本";内部信息可以进行

document.execCommand("副本"(;

但我不知道如何使用var选择

我认为这可以工作

  • 在HTML中
<div class="container">
<div id="messagesIn">
...Some Text
</div>
<button id="buttonShow">Copy</button>
</div>
  • 然后在代码中
var delayBecauseFirebase = 1000;
function copyText(){
//Select your text
var range = document.createRange();
range.selectNode(document.getElementById("messagesIn"));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
//Call copy command
document.execCommand("copy");
}
function addClickListener() {
var buttonShowJ = document.getElementById("buttonShow");
if(buttonShowJ){
buttonShowJ.addEventListener("click", copyText);
}else{
console.error("Copy button not found");
}
}
setTimeout(addClickListener, delayBecauseFirebase);

推荐帖子:

  • 单击鼠标选择所有DIV文本
  • 如何用JavaScript复制到剪贴板

最新更新