一、具體場景
前端有時需要實現點擊按鈕復制的功能,這個時候就不能讓用戶去手動選擇內容右鍵復制了。
二、實現方式
1. document.execCommand
(1)具體實現
復制時,先選中文本,然后調用document.execCommand(‘copy’),選中的文本就會進入剪貼板。這就需要借助輸入框來實現對文本的選中。
具體案例:
<button type="button" onclick="theCopy()">復制</button><label style="display: block"><textarea id="textArea">哈哈哈哈哈哈哈哈哈111111</textarea></label>
function theCopy() {let textArea = document.getElementById('textArea')console.log(textArea);textArea.select()document.execCommand('copy')}
html加js這些就可以實現,但是我又發現另一種寫法!!
如果內容不在輸入框中,我們可以借助一個透明的輸入框來實現?
?
<button type="button" onclick="theCopy()">復制</button><p id="text">哈哈哈哈哈哈哈哈哈111111</p><label style="display: block"><textarea id="textArea" style="opacity: 0;"></textarea></label>
function theCopy() {let textArea = document.getElementById('textArea')let text = document.getElementById('text')textArea.innerText = text.innerHTMLconsole.log(textArea);textArea.select()document.execCommand('copy')}
?
?