input
內的文字api
(兼容問題)這裏使用典型的一種api
,另,爲了能複製div內的文字,就須要咱們經過動態建立input
來實現。api
dom.addEventListener('click',e=>{ // 建立input let input = document.createElement('input'); document.body.appendChild(input); // 塞入內容 input.setAttribute('value', res.innerText); // 選中內容 input.select(); // 執行復制 document.execCommand('copy'); // 移除掉 input document.body.removeChild(input); })
// 選擇某dom內的全部文本 function selectText(el) { if (document.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(el); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(el); selection.removeAllRanges(); selection.addRange(range); } }
dom.addEventListener('click',e=>{ // 建立input let input = document.createElement('input'); document.body.appendChild(input); // 塞入內容 input.setAttribute('value', res.innerText); // 選中內容 input.select(); // 執行復制 document.execCommand('copy'); // 界面上選擇文本 需放在 iput.select()以後,不然會被取消效果 this.selectText(e.target) // 移除掉 input document.body.removeChild(input); })