zoukankan      html  css  js  c++  java
  • 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;
    }
     
    测试,失败,无效,后期更新 
  • 相关阅读:
    vim tab转换成space
    vs计算项目代码总行数
    读取xml文件
    复选框全选、取消全选
    网页上用js禁用鼠标右键
    腾讯、微软、亚马逊测试站点
    限制文本域输入字符个数,即使显示输入字符数和剩余字符数,超出不显示!
    DataUtil
    DES加密解密类
    JsonHelper(Json帮助类)
  • 原文地址:https://www.cnblogs.com/FACESCORE/p/11290190.html
Copyright © 2011-2022 走看看