当前位置: 首页 > news >正文

js复制内容到剪切板

复制内容到剪切板

最近预报一个需求需要点击按钮复制当前到行的内容到剪切板,
所以写了这个工具

export function copyText(text: string, prompt: string | null = '已成功复制到剪切板!') {if (navigator.clipboard) {return navigator.clipboard.writeText(text).then(() => {prompt && console.log(prompt)}).catch((error) => {console.error('复制失败!' + error.message);return error;});}if (Reflect.has(document, 'execCommand')) {return new Promise((resolve, reject) => {try {const textArea = document.createElement('textarea');textArea.value = text;// 在手机 Safari 浏览器中,点击复制按钮,整个页面会跳动一下textArea.style.width = '0';textArea.style.position = 'fixed';textArea.style.left = '-999px';textArea.style.top = '10px';textArea.setAttribute('readonly', 'readonly');document.body.appendChild(textArea);textArea.select();document.execCommand('copy');document.body.removeChild(textArea);prompt && console.log(prompt)resolve();} catch (error) {console.error('复制失败!' + error.message);reject(error);}});}return Promise.reject(`"navigator.clipboard" 或 "document.execCommand" 中存在API错误, 拷贝失败!`);
}
http://www.lryc.cn/news/483311.html

相关文章:

  • 代码 RNN原理及手写复现
  • 企业官网的在线客服,如何提高效果?
  • 「实战应用」如何可视化 DHTMLX Scheduler 中的资源工作量?
  • 论文阅读《BEVFormer》
  • sql专题 之 sql的执行顺序
  • Vue3 -- 基于Vue3+TS+Vite项目【项目搭建及初始化】
  • CTF-RE: TEA系列解密脚本
  • 信号量和线程池
  • 【人工智能】10分钟解读-深入浅出大语言模型(LLM)——从ChatGPT到未来AI的演进
  • 「QT」几何数据类 之 QPointF 浮点型点类
  • 可能是全网第一个MySQL Workbench插件编写技巧
  • D62【python 接口自动化学习】- python基础之数据库
  • 探索美赛:从准备到挑战的详细指南
  • IP地址查询——IP归属地离线库
  • “倒时差”用英语怎么说?生活英语口语学习柯桥外语培训
  • Linux入门攻坚——37、Linux防火墙-iptables-3
  • 微服务架构面试内容整理-安全性-Spring Security
  • 新的服务器Centos7.6 安装基础的环境配置(新服务器可直接粘贴使用配置)
  • 深度学习:广播机制
  • 音视频入门基础:FLV专题(25)——通过FFprobe显示FLV文件每个packet的信息
  • Openstack7--安装消息队列服务RabbitMQ
  • day55 图论章节刷题Part07([53.寻宝]prim算法、kruskal算法)
  • LeetCode 93-复制 IP地址
  • 海底捞点单
  • It’s All About Your Sketch: Democratising Sketch Control in Diffusion Models
  • Java基础-组件及事件处理(下)
  • npm list -g --depth=0(用来列出全局安装的所有 npm 软件包而不显示它们的依赖项)
  • 深度学习:nn.Linear
  • 大数据新视界 -- 大数据大厂之 Impala 性能提升:高级执行计划优化实战案例(下)(18/30)
  • 常用的Anaconda Prompt命令行指令