问题:原生方法document.execCommand('copy')在ios端返回false,不生效,无法实现复制。
<input type="text" id="copy-input" readonly style="position: absolute;left: -1000px; z-index:-1000">
copy() {
let input = document.querySelector('#copy-input');
input.readOnly = "readOnly"; // 防止ios掉起键盘
input.value = location.href; // 要复制的内容
// ios必须先选中文字且不支持 input.select();
this.selectText(input, 0, location.href.length);
if (document.execCommand('copy')) {
document.execCommand('copy');
}else {
console.log('不兼容');
}
input.blur();
},
selectText(textbox, startIndex, stopIndex) {
// 选择文本。createTextRange(setSelectionRange)是input方法
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();
}
}