Copy text string on click

后端 未结 8 1911
我在风中等你
我在风中等你 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"))
        }
      });
    }
    <span class="class">text</span>
    <br>
    <span class="class">text2</span>

    0 讨论(0)
  • 2020-11-27 03:29

    HTML:

    <button type='button' id='btn'>Copy</button>
    

    JS

    document.querySelect('#btn').addEventListener('click', function() {
       copyToClipboard('copy this text');
    });
    

    JS / Function:

    function copyToClipboard(text) {
        var selected = false;
        var el = document.createElement('textarea');
        el.value = text;
        el.setAttribute('readonly', '');
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        document.body.appendChild(el);
        if (document.getSelection().rangeCount > 0) {
            selected = document.getSelection().getRangeAt(0)
        }
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
        if (selected) {
            document.getSelection().removeAllRanges();
            document.getSelection().addRange(selected);
        }
    };
    
    0 讨论(0)
提交回复
热议问题