注意事項
使用 JS 實現復制功能並不是很難,但是有幾個需要注意的地方。
首先文本只有選中才可以復制,所以簡單的做法就是創建一個隱藏的 input
,然后綁定需要復制的文本。
另外如果將 input
設置為 ``type="hidden"或者
display:none則無法選中文本,也就無法復制,可以設置
position:absolute;left:-999px;` 來隱藏文本域。
const copyInput = document.querySelector('#copyInput');
copyInput.value = '需要復制的文本';
copyInput.select();
document.execCommand('Copy');
或者動態創建 input
function copy(str) {
const input = document.createElement("input");
input.readOnly = 'readonly';
input.value = str;
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, input.value.length);
document.execCommand('Copy');
document.body.removeChild(input);
}
移動端禁止鍵盤彈出
在 iOS 中 input
聚焦的時候會彈起鍵盤,對於復制操作交互體驗很差,可以用以下方式禁止鍵盤的彈起。
<input type="text" readonly="readonly" />
<input type="text" onfocus="this.blur()" />
$("#box").focus(function(){
document.activeElement.blur();
});
關於粘貼:除了 IE,現代化的瀏覽器暫時無法讀取剪貼板里的內容。