JavaScript實現文本複製的功能

一、HTML  代碼  注:只能使用input或者textarea等

<div>

      <input type="text"  id='codeInput' readonly>

      <a οnclick='copyClick()'>複製</a>

</div>

二、JavaScript

function copyClick () {

      let inputText = document.getElementById('codeInput'); //獲取input

      inputText.focus(); // 獲取焦點到input

      inputText.setSelectionRange(0, inputText.value.length); //選擇複製的內容

      let isSuccess = document.execCommand('copy', true); //執行復制操作

      inputText.setSelectionRange(0, 0); //取消選擇

     if (isSuccess) {

             this.showAlert('複製成功');

     } else {

             this.showAlert('請手動複製');

     }

}

三、瀏覽器兼容性參考如下

https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/setSelectionRange

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