方法一:推荐
private copyText(text: string) {
// input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法
// 选择文本。createTextRange(setSelectionRange)是input方法
let 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(); //这句也必须
}
}
// 数字没有 .length 不能执行selectText 需要转化成字符串
const textString = text.toString();
let input: any = document.createElement('input');
//input.id = "cp_input";
input.readOnly = "readOnly"; // 防止ios聚焦触发键盘事件
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');
this.utils.showToast("复制成功");
} else {
this.utils.showError('不能使用这种方法复制内容!');
}
//input.blur();
document.body.removeChild(input);
}
方法二:
/**
* 复制内容
* @param {String} value 需要复制的内容
* @param {String} type 元素类型 input, textarea
* 这里主要解决了 ios 下的 bug,以及使用 textarea 来解决换行内容的复制。
*/
private copyContent(value, type = 'input') {
let input: any = document.createElement(type);
input.setAttribute('readonly', 'readonly'); // 设置为只读, 防止在 ios 下拉起键盘
// input.setAttribute('value', value); // textarea 不能用此方式赋值, 否则无法复制内容
input.value = value;
document.body.appendChild(input);
input.setSelectionRange(0, 9999); // 防止 ios 下没有全选内容而无法复制
input.select();
if ((navigator.userAgent.match(/(iPhone|iPod|iPad);?/i))) {
//注意:以下代码在html中测试通过,复制成功,搬入这里就不行了???(Chelen 2022-07-19 以后有时间再处理)
let range = document.createRange();
// 选中需要复制的节点
range.selectNode(input);
// 执行选中元素
const selection = window.getSelection();
if (selection.rangeCount > 0)
selection.removeAllRanges();
selection.addRange(range);
try {
document.execCommand('copy');
this.utils.showToast("复制成功");
} catch (err) {
this.utils.showError('不能使用这种方法复制内容' + err.toString());
}
// 移除选中的元素
selection.removeAllRanges();
}
else {
try {
document.execCommand('copy');
this.utils.showToast("复制成功");
} catch (err) {
this.utils.showError('不能使用这种方法复制内容' + err.toString());
}
}
document.body.removeChild(input);
}