
组件介绍
复制文本到剪贴板应该不难。它不应该需要几十个步骤来配置或数百个KBs来加载。但最重要的是,它不应该依赖于Flash或任何臃肿的框架。
组件安装
1 2
| npm install clipboard --save yarn/pnpm add clipboard -S
|
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
| <input id="foo" value="https://github.com/zenorocha/clipboard.js.git">
<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
|
<textarea id="bar">Mussum ipsum cacilds...</textarea>
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar"> Cut to clipboard </button>
|
1 2 3 4
| <button class="btn" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js"> Copy to clipboard </button>
|
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); });
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| new ClipboardJS('.btn', { target: function(trigger) { return trigger.nextElementSibling; } })
new ClipboardJS('.btn', { text: function(trigger) { return trigger.getAttribute('aria-label'); } })
new ClipboardJS('.btn', { container: document.getElementById('modal') });
clipboard.destroy();
|
组件演示
1 2
| <p id="target"><span>Just because you can doesn't mean you should — clipboard.js</span></p> <p>复制</p>
|
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(); });
|