第一個(gè)方法
copyParameter(content) { // content 要復(fù)制的參數(shù)
var aux = document.createElement("input");
aux.setAttribute("value", content);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);
alert("復(fù)制成功");
},
如果這種方法不行換第二種
const copyText = (text) => {
// 數(shù)字沒(méi)有 .length 不能執(zhí)行selectText 需要轉(zhuǎn)化成字符串
const textString = text.toString();
let input = document.querySelector('#copy-input');
if (!input) {
input = document.createElement('input');
input.id = "copy-input";
input.readOnly = "readOnly"; // 防止ios聚焦觸發(fā)鍵盤事件
input.style.position = "absolute";
input.style.left = "-1000px";
input.style.zIndex = "-1000";
document.body.appendChild(input)
}
input.value = textString;
// ios必須先選中文字且不支持 input.select();
selectText(input, 0, textString.length);
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('已復(fù)制到粘貼板');
}else {
console.log('不兼容');
}
input.blur();
// input自帶的select()方法在蘋果端無(wú)法進(jìn)行選擇地熄,所以需要自己去寫一個(gè)類似的方法
// 選擇文本。createTextRange(setSelectionRange)是input方法
function selectText(textbox, startIndex, stopIndex) {
if (textbox.createTextRange) {//ie
const 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();
}
}
};