copyText()安卓,ios11,ios12均可用 ,而且不弹起输入键盘
// 复制copyText
function copyText(text) {
var input = document.createElement("input");
var currentFocus = document.activeElement;
document.body.appendChild(input);
input.readOnly = 'readonly';
input.value = text;
input.focus();
if (input.setSelectionRange)
input.setSelectionRange(0, input.value.length);
else
input.select();
try {
var flag = document.execCommand("copy");
} catch (eo) {
var flag = false;
}
input.blur();
document.body.removeChild(input);
currentFocus.focus();
currentFocus.blur();
return flag;
}
在 iOS 10 及如下版本 中,使用复制功能有如下限制:ios
- 只能复制
<input>
或 <textarea>
元素中的文本;
- 若是包含待复制文本的元素没有包含在一个
<form>
中,那它的 contentEditable
属性必须为 true
;
- 第2步中的元素同时不能是
readonly
;
- 待复制文本必须是
被选中
状态。
要知足上述4个限制,代码中须要作到:app
- 把待复制文本放入
<input>
或 <textarea>
类型的元素 A 中;
- 保存 A 元素的
contentEditable
和 readonly
属性,以便复制完成后恢复现场;
- 设置 A 元素的
contentEditable
为 true
, readonly
属性为 false
;
- 建立一个
range
对象并挂载 A 元素;
- 获取窗口当前选中元素并清除,而后设置选中元素为第4步建立的
range
对象;
- 视状况恢复元素 A 的
contentEditable
和 readonly
属性;
- 执行
document.execCommand('copy')
。
最终实现代码以下:测试
function copystr(str) {
var el = document.createElement('input');
el.value = str;
el.style.opacity = '0';
document.body.appendChild(el);
var editable = el.contentEditable;
var readOnly = el.readOnly;
el.contentEditable = true;
el.readOnly = false;
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
el.setSelectionRange(0, 999999);
el.contentEditable = editable;
el.readOnly = readOnly;
var flag = document.execCommand('copy');
el.blur();
return flag;
}
测试,失败,无效,后期更新