今天在項(xiàng)目中有一個(gè)一鍵復(fù)制的需求,再網(wǎng)上找了很多的資料,發(fā)現(xiàn)以下的方法很好的實(shí)現(xiàn)了
//一鍵復(fù)制
function copyLink(){
var e = document.getElementById("copy");
? ? e.select(); // 選擇對象
? ? document.execCommand("Copy"); // 執(zhí)行瀏覽器復(fù)制命令
? ? document.activeElement.blur();
}
滿心歡喜的提交測試后,發(fā)現(xiàn)以上的代碼再android中能完美的實(shí)現(xiàn)復(fù)制,但是在ios中確實(shí)不行的,并且在ios中還會有鍵盤被喚起一閃而逝的情況。
一點(diǎn)點(diǎn)的排查原因,終于發(fā)現(xiàn)實(shí)e.select()方法,ios不支持
尋找解決辦法,終于找到了,借鑒了下面這位大神的方法
function selectText(textbox, startIndex, stopIndex) {
if(textbox.createTextRange) {//ie
? ? ? ? var range = textbox.createTextRange();
? ? ? ? range.collapse(true);
? ? ? ? range.moveStart('character', startIndex);//起始光標(biāo)
? ? ? ? range.moveEnd('character', stopIndex - startIndex);//結(jié)束光標(biāo)
? ? ? ? range.select();//不兼容蘋果
? ? }else{//firefox/chrome
? ? ? ? textbox.setSelectionRange(startIndex, stopIndex);
? ? ? ? textbox.focus();
? ? }
}