Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

javascript - How Can I Select A Variable To Copy?

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);

I want to select the "text" inside info to can do

document.execCommand("copy");

But i dont know how can i use select for that var.

question from:https://stackoverflow.com/questions/65600763/how-can-i-select-a-variable-to-copy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think this could work

  • In the HTML
<div class="container">
  <div id="messagesIn">
    ...Some Text
  </div>
  <button id="buttonShow">Copy</button>
</div>
  • Then in the code
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);

Recomended post:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...