javascript復制到黏貼板之完美兼容
很多時候我們需要給用戶方便,提供一鍵復制的功能,但是在實現的過程中遇到各式各樣的坑。
原生解決方案
document.execCommand()方法
MDN
上的定義:
which allows one to run commands to manipulate the contents of the editable region.
當一個HTML文檔切換到設計模式 (designMode)時,document暴露 execCommand 方法,該方法允許運行命令來操縱可編輯區域的內容。
使用方式
函數語法:
bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
- aCommandName :表示命令名稱,比如: copy, cut 等(更多命令訪問);
- aShowDefaultUI:是否展示用戶界面,一般為 false。Mozilla 沒有實現;
- aValueArgument:一些命令(例如insertImage)需要額外的參數(insertImage需要提供插入image的url),默認為null;
兼容性
目前除了 安卓UC瀏覽器、Opera Mini、安卓原生瀏覽器 外其他都支持。
使用教程
- 如果目標是
input
元素
<!--html-->
<input id="demoInput" value="hello world">
<button id="btn">點我復制</button>
<!--JavaScript-->
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {const input = document.querySelector('#demoInput');input.select();if (document.execCommand('copy')) {document.execCommand('copy');console.log('復制成功');}
})
- 如果目前是非
input
元素
<!--html-->
<button id="btn" (click)="copy()">點我復制</button>
<span id="copy-text"></span>
<!--JavaScript-->
function copy() {const content = document.getElementById('copy-text');const input = document.createElement('input');input.setAttribute('readonly', 'readonly');input.setAttribute('value', content.innerHTML);document.body.appendChild(input);input.focus();input.setSelectionRange(0, input.value.length);if (document.execCommand('copy')) {document.execCommand('copy');console.log("復制成功");} else {console.log("復制失敗");}document.body.removeChild(input);
}
遇到的坑:
-
復制的時候,ios手機會出現鍵盤彈出又瞬間收回。這是因為輸入框聚焦造成的。
解決辦法,增加下面一段,讓
input
只讀不能輸入,就不會出現了。input.setAttribute('readonly', 'readonly');
-
input.select()
在ios
下不能選中全部內容,更換input.setSelectionRange(0, input.value.length);
方法。
END