需求場景
使用document.execCommand()方法,以下簡稱為“命令API”。
示例一
HTML部分
<input type="text" id="text_input" />
<button type="button" id="copy_text">copy</button>
JavaScript部分
var inputElem = document.getElementById('text_input');
var btnElem = document.getElementById('copy_text');
btnElem.addEventListener('click', function() {
if(!document.execCommand) {
console.error('copy unsupport');
return;
}
inputElem.select();
var result = document.execCommand('copy');
if(result) {
console.log('copy success');
} else {
console.error('copy fail');
}
});
示例二
實際開發中,需要復制的內容通常是文本元素中的文本。此時,可以使用一個不在可見區域內的表單元素來變向實現。
HTML部分
<input type="text" id="text_input" />
<p>paragraph</p>
<button type="button" id="copy_text">copy</button>
CSS部分
#text_input {
position: absolute;
top: -100px;
}
JavaScript部分
var inputElem = document.getElementById('text_input');
var btnElem = document.getElementById('copy_text');
var textElem = document.querySelector('p');
btnElem.addEventListener('click', function() {
if(!document.execCommand) {
console.error('當前環境不支持復制功能');
return;
}
inputElem.value = textElem.innerText;
inputElem.select();
var result = document.execCommand('copy');
if(result) {
console.log('copy success');
} else {
console.error('copy fail');
}
});
與例子一的差別在於,選中表單元素前,需要對其進行賦值操作。
注意事項
- 檢測當前環境是否支持命令API,這一步不可或缺。
- 瀏覽器環境不支持命令API,需要合理地提示用戶手動進行復制操作。所以,一定不能設置文本元素
user-select: none;
,這樣會使文本不能被選擇。 - 表單元素必須處於被選中狀態,即調用
inputElement.select()
方法,文本元素沒有select()
方法。 - 經測試,不能使用
display: none;
或visibility: hidden;
來隱藏表單元素。所以,只能將此表單元素,定位至可以見區域之外。
更多方案
- clipboard.js:不依賴flash的一個插件。實現原理和上面的例子是類似的,使用插件可以簡化很多開發工作。