clipboard.js 中文文档

clipboard.js是一款使用简单的粘贴复制插件,它不依赖于Flash或其他框架,在github拥有3万多颗星可见其优秀程度,我们将介绍在umdvue环境下如何使用它。

官方网站

https://github.com/zenorocha/clipboard.js

安装方式

npm install clipboard --save

文件下载

如果你不想通过npm命令安装,也可以直接下载文件
 下载 clipboard.js

引用方式

//方法一:
<script src="https://www.itxst.com/package/clipboardjs/clipboard.min.js"></script>
//方法二:
import Clipboard from "clipboard"

兼容性

使用方法

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>clipboard例子</title> 
    <script src="https://www.itxst.com/package/clipboardjs/clipboard.min.js"></script>
</head>
<body style="padding:10px;">
    <input id="foo" value="https://www.itxst.com"/>
    <!-- Trigger -->
    <input class="btn" id="btn" data-clipboard-target="#foo" type="button"  value="复制">
    <script>
        //初始化对象
        var clipboard = new ClipboardJS('.btn');
        clipboard.on('success', function (e) {
            console.info('Action:', e.action);
            console.info('Text:', e.text);
            console.info('Trigger:', e.trigger);
            //注销对象
            e.clearSelection();
            document.getElementById("btn").value="复制成功";
        });

        clipboard.on('error', function (e) {
            console.error('Action:', e.action);
            console.error('Trigger:', e.trigger);
            document.getElementById("btn").value="复制失败";
        });
    </script> 
</body>
</html>

在线试一试

vue3中使用方法

<template>
  <div class="itxst">
    <div>
      <input v-model="state.message" />
      <input class="btn" @click="copy" type="button" value="复制" />
    </div>
  </div>
</template>
<script setup>
import { ref, reactive } from "vue";
import Clipboard from "clipboard";

const state = reactive({
  message: "https://www.itxst.com",
});
//复制方法,本例子是vue3环境下,同样在vue2中也可以使用
const copy = () => {
  let clipboard = new Clipboard(".itxst", {
    text: () => {
      //返回需要复制的字符串
      return state.message;
    },
  });
  clipboard.on("success", () => {
    clipboard.destroy();
  });
  clipboard.on("error", () => {
    clipboard.destroy();
  });
};
</script>
<style scoped>
</style>

在线试一试