一键复制功能在iOS手机实现

第一个方法

copyParameter(content) {     // content 要复制的参数
    var aux = document.createElement("input");
    aux.setAttribute("value", content);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("copy");
    document.body.removeChild(aux);
     alert("复制成功");
  
   },

如果这种方法不行换第二种

 const copyText = (text) => {
    // 数字没有 .length 不能执行selectText 需要转化成字符串
    const textString = text.toString();
    let input = document.querySelector('#copy-input');
    if (!input) {
      input = document.createElement('input');
      input.id = "copy-input";
      input.readOnly = "readOnly";        // 防止ios聚焦触发键盘事件
      input.style.position = "absolute";
      input.style.left = "-1000px";
      input.style.zIndex = "-1000";
      document.body.appendChild(input)
    }

    input.value = textString;
    // ios必须先选中文字且不支持 input.select();
    selectText(input, 0, textString.length);
    if (document.execCommand('copy')) {
      document.execCommand('copy');
      alert('已复制到粘贴板');
    }else {
      console.log('不兼容');
    }
    input.blur();

    // input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法
    // 选择文本。createTextRange(setSelectionRange)是input方法
    function selectText(textbox, startIndex, stopIndex) {
      if (textbox.createTextRange) {//ie
        const range = textbox.createTextRange();
        range.collapse(true);
        range.moveStart('character', startIndex);//起始光标
        range.moveEnd('character', stopIndex - startIndex);//结束光标
        range.select();//不兼容苹果
      } else {//firefox/chrome
        textbox.setSelectionRange(startIndex, stopIndex);
        textbox.focus();
      }
    }
  };

链接:https://segmentfault.com/a/1190000019525962

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 29,033评论 1 45
  • 前言 针对面试的 JavaScript 知识点整理 1.介绍一下js的数据类型有哪些,值是如何存储的 JavaSc...
    Moon_f3e1阅读 300评论 0 0
  • 基础知识 – 四大组件(生命周期,使用场景,如何启动)java基础 – 数据结构,线程,mvc框架通信 – 网络连...
    跑步的小男孩阅读 293评论 0 2
  • 面试,无非都是问上面这些问题(挺多的 - -!),聘请中高级的安卓开发会往深的去问,并且会问一延伸二。以下我先提出...
    那年的歌阅读 543评论 0 0
  • 目录介绍 6.0.0.1 运行时数据区域有哪些?Java虚拟机栈是做什么的?本地方法栈又是做什么的? 6.0.0....
    杨充211阅读 496评论 0 1

友情链接更多精彩内容