clipboard.js将文本复制到剪贴板应该不难。它不需要几十个步骤来配置,也不需要数百个KB来加载。但最重要的是,它不应该依赖于Flash或任何臃肿的框架。

这就是clipboard.js存在的原因

目录

效果

一、准备工作

1、安装依赖包

2、示例版本 

二、使用步骤

1、在index.html文件中引入依赖包

2、单文件使用

三、完整示例

  欢迎扫描下方二维码关注VX公众号


 

官方文档clipboard.js — Copy to clipboard without Flash

clipboard.js — Copy to clipboard without FlashCopy text to the clipboard shouldn't be hard. It shouldn't require dozens of steps to configure or hundreds of KBs to load. But most of all, it shouldn't depend on Flash or any bloated framework. That's why clipboard.js exists.icon-default.png?t=N7T8https://clipboardjs.com/

浏览器兼容

 图片来源:JavaScript 实现复制功能 | 菜鸟教程

效果

一、准备工作

1、安装依赖包

npm install clipboard --save

2、示例版本 

"clipboard": "^2.0.8"

二、使用步骤

1、在index.html文件中引入依赖包

代码如下(示例):

<script type=“text/javascript” src="dist/clipboard.min.js"></script>

2、单文件使用

代码如下(示例):

import ClipboardJS from 'clipboard';
const clipboard = new ClipboardJS('.btn');

clipboard.on('success', function(e) {
  console.log(e);
  console.info('Text:', e.text);
  message.info('复制成功');
  e.clearSelection();
});

clipboard.on('error', function(e) {
  if(!e.text) message.error('暂无可复制的内容')
});

三、完整示例

index.html

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>XXX</title>
    <script type=“text/javascript” src="dist/clipboard.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
</html>

Clipboard.vue

<template>
  <a-tooltip>
    <template #title>点击复制</template>
    <span style="margin: 5px 8px;">
      <span class="copy" style="cursor: pointer;" :data-clipboard-text="coord">{{coord}}</span>
    </span>
  </a-tooltip>
</template>

<script lang="ts" setup>
  import { ref, onBeforeUnmount } from 'vue';
  import { message } from 'ant-design-vue';
  import ClipboardJS from 'clipboard';
   
  const coord = ref('这里是可以点击复制的文本内容哦');
  const clipboard = new ClipboardJS('.copy');

  clipboard.on('success', function(e) {
    console.log(e);
    console.info('Text:', e.text);
    message.info('复制成功');
    e.clearSelection();
  });

  clipboard.on('error', function(e) {
    if(!e.text) message.error('暂无可复制的内容')
  });

  onBeforeUnmount(() => {
    clipboard.destroy();
  })
</script>

  欢迎扫描下方二维码关注VX公众号

Logo

前往低代码交流专区

更多推荐