var copy = function () {
let copyId = String(new Date().getTime())
let input = document.getElementById(copyId);
if (!input) {
input = document.createElement('input');
input.id = copyId;
input.readOnly = "readOnly"; // 防止ios聚焦觸發鍵盤事件
input.style.position = "absolute";
input.style.left = "-1000px";
input.style.zIndex = "-1000";
document.body.appendChild(input)
}
let copyText = "WXTRDFDE"; // 需要複制的内容
input.value = copyText;
// ios必須先選中文字且不支援 input.select();
selectText(input, 0, copyText.length);
if (document.execCommand('copy')) {
document.execCommand('copy');
alert('複制成功!');
} else {
alert('複制失敗!');
}
input.blur();
// input自帶的select()方法在蘋果端無法進行選擇,是以需要自己去寫一個類似的方法
// 選擇文本。createTextRange(setSelectionRange)是input方法
function selectText(textbox, startIndex, stopIndex) {
if (textbox.createTextRange) {//ie
const range = textbox.createTextRange();
range.collapse(true);
range.moveStart('character', startIndex);//起始光标
range.moveEnd('character', stopIndex - startIndex);//結束光标
range.select();//不相容蘋果
} else {//firefox/chrome
textbox.setSelectionRange(startIndex, stopIndex);
textbox.focus();
}
}
}