前端插件Clipboard.js现代化拷贝(复制)文字

组件介绍

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

组件安装

  • 依赖(包)管理工
1
2
npm install clipboard --save
yarn/pnpm add clipboard -S
  • CDN直接引入
1
<script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script>

组件使用

  • Copy text from another element
1
2
3
4
5
6
7
<!-- Target -->
<input id="foo" value="https://github.com/zenorocha/clipboard.js.git">

<!-- Trigger -->
<button class="btn" data-clipboard-target="#foo">
<img src="assets/clippy.svg" alt="Copy to clipboard">
</button>
  • Cut text from another element
1
2
3
4
5
6
7
8
<!-- input/textarea -->
<!-- Target -->
<textarea id="bar">Mussum ipsum cacilds...</textarea>

<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
Cut to clipboard
</button>
  • Copy text from attribute
1
2
3
4
<!-- Trigger -->
<button class="btn" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
Copy to clipboard
</button>
  • Events
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
});

clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
  • Advanced Usage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// target
new ClipboardJS('.btn', {
target: function(trigger) {
return trigger.nextElementSibling;
}
})

// text
new ClipboardJS('.btn', {
text: function(trigger) {
return trigger.getAttribute('aria-label');
}
})

// container
new ClipboardJS('.btn', {
container: document.getElementById('modal')
});

clipboard.destroy();

组件演示

  • html
1
2
<p id="target"><span>Just because you can doesn't mean you should — clipboard.js</span></p>
<p>复制</p>
  • javascript
1
2
3
4
5
6
7
8
9
const clipboard = new ClipboardJS('#copy-btn', {
target: function(trigger) {
return document.querySelector('#target') // 返回文本(带格式)
}
});
clipboard.on('success', function(e) {
console.log('复制成功')
e.clearSelection();
});