当前位置:网站首页>js 实现复制功能
js 实现复制功能
2022-08-01 00:24:00 【GMLGDJ】
<body>
<button>复制</button>
<script>
const copy = (value, cb) => {
// 动态创建 textarea 标签
const textarea = document.createElement('textarea')
// 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
textarea.readOnly = 'readonly'
textarea.style.position = 'absolute'
textarea.style.left = '-9999px'
// 将要 copy 的值赋给 textarea 标签的 value 属性
// 网上有些例子是赋值给innerText,这样也会赋值成功,但是识别不了\r\n的换行符,赋值给value属性就可以
textarea.value = value
// 将 textarea 插入到 body 中
document.body.appendChild(textarea)
// 选中值并复制
textarea.select()
textarea.setSelectionRange(0, textarea.value.length)
document.execCommand('Copy')
document.body.removeChild(textarea)
if (cb && Object.prototype.toString.call(cb) === '[object Function]') {
cb()
}
}
const btn = document.getElementsByTagName('button')[0];
btn.addEventListener('click', (e) => {
console.log(e);
copy(123, () => {
console.log('复制成功');
})
})
</script>
</body>
边栏推荐
- 逐步手撕轮播图3(保姆级教程)
- 继承的注意事项
- SQL injection Less47 (error injection) and Less49 (time blind injection)
- Thinking and Implementation of Object Cache Service
- lua入门案例实战1234定义函数与标准函数库功能
- An open source and easy-to-use flowchart drawing tool drawio
- Carefully organize 16 MySQL usage specifications to reduce problems by 80% and recommend sharing with the team
- LeetCode--打家劫舍问题
- mysql having的用法
- 面试题:实现死锁
猜你喜欢
随机推荐
/usr/local/bin和/usr/bin的区别
Matlab / ArcGIS 处理GPM全球月均降水数据
面试突击69:TCP 可靠吗?为什么?
MYSQL索引解析
thymeleaf迭代map集合
When can I use PushGateway
类和对象:中
Inheritance and friend, static member relationship
什么是动态规划,什么是背包问题
[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories
Recommendation system: Summary of common evaluation indicators [accuracy rate, precision rate, recall rate, hit rate, (normalized depreciation cumulative gain) NDCG, mean reciprocal ranking (MRR), ROC
An open source and easy-to-use flowchart drawing tool drawio
/etc/sysconfig/network-scripts 配置网卡
MYSQL二阶段提交
如何设计高可用高性能中间件 - 作业
逐步手撕轮播图3(保姆级教程)
【云驻共创】【HCSD大咖直播】亲授大厂面试秘诀
NIO编程
Difference between first and take(1) operators in NgRx
欧拉系统(euleros):升级Mysql