• 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;
    }
     
    测试,失败,无效,后期更新 
  • 相关阅读:
    微信支付(APP支付)-服务端开发(一)
    C#去除HTML标签
    监视EntityFramework中的sql流转你需要知道的三种方式Log,SqlServerProfile, EFProfile
    SQL总结(六)触发器
    sql中索引不会被用到的几种情况
    Sql Server参数化查询之where in和like实现详解
    Sql Server查询性能优化之不可小觑的书签查找
    浅析Sql Server参数化查询
    Sql Server查询性能优化之走出索引的误区
    IScroll在某些win10版本下的奇怪问题
  • 原文地址:https://www.cnblogs.com/FACESCORE/p/11290190.html
Copyright © 2020-2023  润新知