原理
自動複製到剪貼板可以分兩步走:自動選中
,複製到剪貼板
<input>
標籤可以自動選中文本框內的文本,然後通過document.execCommand('copy')
實現自動複製,或者,直接使用Navigator.clipboard
操作剪貼板,可以寫入和讀取任意數據
- document.execCommand是一個同步命令,在w3c中記爲將要廢棄的接口
- Navigator.clipboard 使用Promise,是一個在草案階段的剪貼板相關的接口
實現
任意文本自動複製-使用Input標籤實現
function copyText(text) {
let textarea = document.createElement("input");//創建input元素
const currentFocus = document.activeElement;//當前獲得焦點的元素,保存一下
document.body.appendChild(textarea);//添加元素
textarea.value = text;
textarea.focus();
textarea.setSelectionRange(0, textarea.value.length);//獲取光標起始位置到結束位置
//textarea.select(); 這個是直接選中所有的,效果和上面一樣
try {
var flag = document.execCommand("copy");//執行復制
} catch(eo) {
var flag = false;
}
document.body.removeChild(textarea);//刪除元素
currentFocus.focus(); //恢復焦點
return flag;
}
任意元素內容自動複製-使用 Selection.addRange() +Navigator.clipboard實現
function copy(text)
{
navigator.clipboard.writeText(text).then(()=>{
alert("成功")
})
.catch(err=>
{
console.error("出錯")
})
}
使用這個接口需要注意,這個接口尚未進入w3c標準,並且僅能在https協議頁面內使用,詳細可見Unblocking Clipboard Access
As with many new APIs, navigator.clipboard is only supported for pages served over HTTPS. To help prevent abuse, clipboard access is only allowed when a page is the active tab. Pages in active tabs can write to the clipboard without requesting permission, but reading from the clipboard always requires permission.
注意 ,Document.execCommand()這個方法被標記爲不推薦的,未來可以使用Navigator.clipboard來實現剪貼功能