angular2+ 的複製

今天在做項目的時候遇到點擊複製的一個功能,雖然原生js的點擊複製只需要三行就搞定了,但是在angular裏面並不生效,於是在網上找了半天,也沒有找到答案,最後無意間看見了大漠老師的視頻,纔有所啓發。

下面是原生的點擊複製方法:

  function copyUrl2(){
    var copyInnerHTML = document.getElementById('invite_code');
    copyInnerHTML.select();
    document.execCommand('copy');

  }

在下面是angular的複製:

 

// 點擊複製
function copyToClipboard(str) {
    console.log(str)
    const el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);

    if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章