使用原生 JS 复制文本兼容移动端 iOS & android
注意事项
使用 JS 实现复制功能并不是很难,但是有几个需要注意的地方。
首先文本只有选中才可以复制,所以简单的做法就是创建一个隐藏的 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);
}
移动端禁止键盘弹出
在 iOS 中 input
聚焦的时候会弹起键盘,对于复制操作交互体验很差,可以用以下方式禁止键盘的弹起。
<input type="text" readonly="readonly" />
<input type="text" onfocus="this.blur()" />
$("#box").focus(function(){
document.activeElement.blur();
});
关于粘贴:除了 IE,现代化的浏览器暂时无法读取剪贴板里的内容。
感谢您的阅读,如果您对我的文章感兴趣,可以关注我的博客,我是叙帝利,下篇文章再见!
低代码平台必备轻量级 GUI 库 https://github.com/acrodata/gui
适用于 Angular 的 CodeMirror 6 组件 https://github.com/acrodata/code-editor
适用于 Angular 的水印组件(防删除,盲水印) https://github.com/acrodata/watermark
支持拖拽和缩放的弹窗组件 https://github.com/acrodata/rnd-dialog
开发低代码平台的必备拖拽库 https://github.com/ng-dnd/ng-dnd
基于 Angular Material 的中后台管理框架 https://github.com/ng-matero/ng-matero
Angular Material Extensions 扩展组件库 https://github.com/ng-matero/extensions
Unslider 轮播图插件纯 JS 实现 https://github.com/nzbin/unsliderjs
仿 Windows 照片查看器插件 https://github.com/nzbin/photoviewer
仿 Windows 照片查看器插件 jQuery 版 https://github.com/nzbin/magnify
完美替代 jQuery 的模块化 DOM 库 https://github.com/nzbin/domq
简化类名的轻量级 CSS 框架 https://github.com/nzbin/snack
与任意 UI 框架搭配使用的通用辅助类 https://github.com/nzbin/snack-helper
单元素纯 CSS 加载动画 https://github.com/nzbin/three-dots
有趣的 jQuery 卡片抽奖插件 https://github.com/nzbin/CardShow
悬疑科幻电影推荐 https://github.com/nzbin/movie-gallery
锻炼记忆力的小程序 https://github.com/nzbin/memory-stake
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?