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();
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理