前端实现将内容复制到剪切板的实现方法(个人项目使用)

复制代码
export const writeStringToClipboard =(text:string)=>{
    const el=document.createElement('textarea');
    el.value=text;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
}

其中, document.execCommand已经被废弃了,不建议使用了,所以推荐使用下面的新方法 :

复制代码
async function copyTextToClipboard(text) {  
    try {  
      await navigator.clipboard.writeText(text);  
      console.log('Text copied to clipboard');  
    } catch (err) {  
      console.error('Failed to copy text: ', err);  
    }  
  }  
    
  // 使用方法  
  copyTextToClipboard('测试复制功能');

是不简单多了一下子.

相关推荐
2601_958492553 小时前
Optimizing Engagement with Freehead Skate - HTML5 Game - Construct 3
前端·html·html5
茉莉玫瑰花茶4 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
zhangxingchao4 小时前
AI应用开发六:企业知识库
前端·人工智能·后端
山峰哥5 小时前
SQL慢查询调优实战:从全表扫描到索引覆盖的完整复盘
前端·数据库·sql·性能优化
红尘散仙5 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
moshuying5 小时前
AI Coding 最大的 token 黑洞,可能根本不是 prompt
前端
红尘散仙5 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
lichenyang4535 小时前
HarmonyOS HMRouter 接入记录:从普通 Tab Demo 到路由跳转
前端
木斯佳6 小时前
前端八股文面经大全:腾讯WXG暑期前端一面(2026-05-15)·面经深度解析
前端·面试·笔试