将文字复制到剪切板

笔者在开发过程中遇到点击按钮之后将文字复制到剪切板的需求,先将按钮的回调函数封装起来,便于以后使用,需要的朋友可以自取~

js 复制代码
  const _copyToClipboard = staticPart => dynamicPart => {
    if (!dynamicPart) return;
    const textToCopy = `${staticPart}${dynamicPart}`;
    const tempInput = document.createElement('input');
    tempInput.value = textToCopy;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand('copy');
    document.body.removeChild(tempInput);
  };

这个函数将复制到剪切板中的内容分成两个部分:静态的和动态的,因此在使用的时候可以这样做:

js 复制代码
const copyFunc = _copyToClipboard('http://localhost:3000/api?id=');
copyFunc('678');
copyFunc('123');
相关推荐
wyzqhhhh1 天前
组件库打包工具选型(npm/pnpm/yarn)的区别和技术考量
前端·npm·node.js
码上暴富1 天前
vue2迁移到vite[保姆级教程]
前端·javascript·vue.js
土了个豆子的1 天前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
全栈技术负责人1 天前
Hybrid应用性能优化实战分享(本文iOS 与 H5为例,安卓同理)
前端·ios·性能优化·html5
xw51 天前
移动端调试上篇
前端
伍哥的传说1 天前
Lodash-es 完整开发指南:ES模块化JavaScript工具库实战教程
大数据·javascript·elasticsearch·lodash-es·javascript工具库·es模块·按需导入
@菜菜_达1 天前
Lodash方法总结
开发语言·前端·javascript
GISer_Jing1 天前
低代码拖拽实现与bpmn-js详解
开发语言·javascript·低代码
YAY_tyy1 天前
基于 Vue3 + VueOffice 的多格式文档预览组件实现(支持 PDF/Word/Excel/PPT)
前端·javascript·vue.js·pdf·word·excel
Yvonne爱编码1 天前
AJAX入门-AJAX 概念和 axios 使用
前端·javascript·ajax·html·js