Copy string to clipboard initiated by click on injected element in JavaScript

后端 未结 2 1575
甜味超标
甜味超标 2021-01-16 07:30

Further to this question: Copy to clipboard with jQuery/js in Chrome

The code from the above question works perfectly for copying a string to clipboard with JavaScr

相关标签:
2条回答
  • 2021-01-16 07:59

    You need to on the event to a dynamically created element. Try this:

    $('#test4').on("click", function() {
      //Your copy code  here
    });
    
    0 讨论(0)
  • 2021-01-16 08:01

    Use e.originalEvent.clipboardData to get original event, and not jQuery event object

    var elem = document.getElementById('test');
    var elem2 = document.getElementById('test2');
    var elem3 = document.getElementById('test3');
    elem.onmouseup = function () {
        document.execCommand('copy');
    }
    
    elem2.addEventListener('copy', function (e) {
        e.preventDefault();
        if (e.clipboardData) {
            e.clipboardData.setData('text/plain', 'custom content');
        } else if (window.clipboardData) {
            window.clipboardData.setData('Text', 'custom content');
        }
    
    });
    
    elem3.onclick = function () {
        document.execCommand('copy');
    }
    
    elem3.addEventListener('copy', function (e) {
        e.preventDefault();
        if (e.clipboardData) {
            e.clipboardData.setData('text/plain', 'bonk custom contentt');
        } else if (window.clipboardData) {
            window.clipboardData.setData('Text', 'bonkcustom content from click');
        }
    });
    $('body').prepend('<div id="test4" title="Click to copy text RAINBOX to clipboard">?</div>');
    $(document).on('click', '#test4', function(e){
        document.execCommand('copy');
    });
    $(document).on('copy', '#test4', function(e){
        e.preventDefault();
        if (e.originalEvent.clipboardData) {
            e.originalEvent.clipboardData.setData('text/plain', 'Over the rainbox');
        } else if (window.clipboardData) {
            window.clipboardData.setData('Text', 'Rainbox');
        }
    });
    #test4{display:inline-block;background-color:tomato;font-size:1.2rem;padding:0 5px;border-radius:3px;cursor:pointer;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    <div id='test'>Select text, it'll copy on mouse up</div>
    <div id='test2'>Copy text using ctrl-c</div>
    <div id='test3'>Click here to copy text</div>
    <div id='ta'><textarea cols="40" rows="5" placeholder="Test pasting here"></textarea></div>

    0 讨论(0)
提交回复
热议问题