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();
});
 
 
 
posted @   假装学习  阅读(338)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示