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 及以下版本 中,使用復制功能有以下限制:

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

要滿足上述4個限制,代碼中需要做到:

  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;
}
 
測試,失敗,無效,后期更新 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM