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();
});
 
 
 
原文地址:https://www.cnblogs.com/FACESCORE/p/11238738.html