Click button copy to clipboard using jQuery

前端 未结 21 2078
醉话见心
醉话见心 2020-11-21 23:11

How do I copy the text inside a div to the clipboard? I have a div and need to add a link which will add the text to the clipboard. Is there a solution for this?

         


        
21条回答
  •  无人共我
    2020-11-22 00:14

    Pure JS, without inline onclick, for paired classes "content - copy button". Would be more comfortable, if you have many elements)

    (function(){
    
    /* Creating textarea only once, but not each time */
    let area = document.createElement('textarea');
    document.body.appendChild( area );
    area.style.display = "none";
    
    let content = document.querySelectorAll('.js-content');
    let copy    = document.querySelectorAll('.js-copy');
    
    for( let i = 0; i < copy.length; i++ ){
      copy[i].addEventListener('click', function(){
        area.style.display = "block";
        /* because the classes are paired, we can use the [i] index from the clicked button,
        to get the required text block */
        area.value = content[i].innerText;
        area.select();
        document.execCommand('copy');   
        area.style.display = "none";
    
        /* decorative part */
        this.innerHTML = 'Copied';
        /* arrow function doesn't modify 'this', here it's still the clicked button */
        setTimeout( () => this.innerHTML = "Copy", 2000 );
      });
    }
    
    })();
    hr { margin: 15px 0; border: none; }
    1111
    
    
    2222
    3333

    Older browser support:

    (function(){
    
    var area = document.createElement('textarea');
    document.body.appendChild( area );
    area.style.display = "none";
    
    var content = document.querySelectorAll('.js-content');
    var copy    = document.querySelectorAll('.js-copy');
    
    for( var i = 0; i < copy.length; i++ ){
      copyOnClick(i);
    }
    
    function copyOnClick(i){
      copy[i].addEventListener('click', function(){
        area.style.display = "block";
        area.value = content[i].innerText;
        area.select();
        document.execCommand('copy');   
        area.style.display = "none";
        
        var t = this;
        t.innerHTML = 'Copied';
        setTimeout( function(){
          t.innerHTML = "Copy"
        }, 2000 );
      });
    }
    
    })();
    hr { margin: 15px 0; border: none; }
    1111
    
    
    2222
    3333

提交回复
热议问题