Copy text string on click

后端 未结 8 1962
我在风中等你
我在风中等你 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:29

    HTML:

    
    

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

提交回复
热议问题