zoukankan      html  css  js  c++  java
  • JS 复制文本兼容移动端 iOS & android

    有几个需要注意的地方。

    首先文本只有选中才可以复制,所以简单的做法就是创建一个隐藏的 input,然后绑定需要复制的文本。

    另外如果将 input 设置为 `type="hidden" 或者 display:none 则无法选中文本,也就无法复制,可以设置 position:absolute;left:-999px; 来隐藏文本域。

    静态复制

    const copyInput = document.querySelector('#copyInput');

    copyInput.value = '需要复制的文本'
    copyInput.select();
    document.execCommand('Copy');
     
    动态创建 input
    function copy(str) {
        const input = document.createElement("input");
        input.readOnly = 'readonly';
        input.value = str;
        document.body.appendChild(input);
        input.select();
        input.setSelectionRange(0, input.value.length);
        document.execCommand('Copy');
        document.body.removeChild(input);
    }
    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 中 input 聚焦的时候会弹起键盘,对于复制操作交互体验很差,可以用以下方式禁止键盘的弹起。
    <input type="text" readonly="readonly" />
    <input type="text" onfocus="this.blur()" />
    const input = document.createElement("input");
         input.readOnly = 'readonly';
    $("#box").focus(function(){
        document.activeElement.blur();
    });
     
     
     
  • 相关阅读:
    习题1
    实验3阅读下面程序、分析说明运行结果,并上机验证。
    实验2利用循环计算n个圆柱体体积。
    实验1编写求圆面积的程序,要求当输入的半径r<=0时,提示输入错误,要求r为浮点型,r的数值是动态的由键盘输入;
    例7-12
    例 7-11
    例7-9
    例7-8
    例7-7
    例7-6
  • 原文地址:https://www.cnblogs.com/FACESCORE/p/11238738.html
Copyright © 2011-2022 走看看