ios9.3.3版本下 document.execCommand("copy") 失敗

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

  1. 只能複製 <input> 或 <textarea> 元素中的文本;
  2. 若是包含待複製文本的元素沒有包含在一個 <form> 中,那它的 contentEditable 屬性必須爲 true 
  3. 第2步中的元素同時不能是 readonly 
  4. 待複製文本必須是 被選中 狀態。

要知足上述4個限制,代碼中須要作到:app

  1. 把待複製文本放入 <input> 或 <textarea> 類型的元素 A 中;
  2. 保存 A 元素的 contentEditable 和 readonly 屬性,以便複製完成後恢復現場;
  3. 設置 A 元素的 contentEditable 爲 true , readonly 屬性爲 false 
  4. 建立一個 range 對象並掛載 A 元素;
  5. 獲取窗口當前選中元素並清除,而後設置選中元素爲第4步建立的 range 對象;
  6. 視狀況恢復元素 A 的 contentEditable 和 readonly 屬性;
  7. 執行 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;
}
 
測試,失敗,無效,後期更新 
相關文章
相關標籤/搜索