Copy text string on click

后端 未结 8 1957
我在风中等你
我在风中等你 2020-11-27 02:31

I spent a good 20 min searching online for this, but couldn\'t find it. What I want is to to be able to copy a text string on click without a button. The text strin

8条回答
  •  無奈伤痛
    2020-11-27 03:27

    guest271314's answer applied to multiple elements:

    spans = document.querySelectorAll(".class");
    for (const span of spans) {
      span.onclick = function() {
        document.execCommand("copy");
      }
    
      span.addEventListener("copy", function(event) {
        event.preventDefault();
        if (event.clipboardData) {
          event.clipboardData.setData("text/plain", span.textContent);
          console.log(event.clipboardData.getData("text"))
        }
      });
    }
    text
    
    text2

提交回复
热议问题