介紹
clipboard.js是一款不依賴flash或任何重量級框架的粘貼複製插件,並且它沒有任何非常複雜的配置,這也是它存在的原因。
安裝
- 通過npm安裝(或者直接下載js文件引入)
npm install clipboard –save
2.引入js
<script src=”dist/clipboard.min.js”></script>
//官網提供了下載地址,也可以使用免費的cdn
使用
示例
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
rel="stylesheet"
/>
</head>
<body>
<div class="input-group" style="width: 600px;margin:200px">
<input
type="text"
class="form-control"
id="foo"
value="https://github.com/zenorocha/clipboard.js.git"
placeholder="Amount"
/>
<div class="btn input-group-addon" data-clipboard-target="#foo">複製</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
new ClipboardJS(".btn");
</script>
</body>
</html>

如圖書最簡單的例子,單機複製按鈕即可自動複製文本框的內容
換成下面就會變成剪切,主要是以下屬性
data-clipboard-action=”cut”
<div class="input-group" style="width: 600px;margin:200px">
<input
type="text"
class="form-control"
id="foo"
value="https://github.com/zenorocha/clipboard.js.git"
placeholder="Amount"
/>
<div class="btn input-group-addon" data-clipboard-target="#foo" data-clipboard-action="cut">剪切</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
new ClipboardJS(".btn");
</script>
剪切操作僅適用於<input>或<textarea>元素
或者這樣,直接複製 data-clipboard-text屬性的內容
<button class="btn" data-clipboard-text="要複製的內容"> 複製 </button>
事件監聽,可以打開控制台自行嘗試
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);
});
高級用法
- 動態綁定
new ClipboardJS('.btn', {
target: function(trigger) {
return trigger.nextElementSibling;
}
});
- 動態賦值
new ClipboardJS('.btn', {
text: function(trigger) {
return trigger.getAttribute('aria-label');
}
});
- 要在Bootstrap Modals中使用或與任何其他更改焦點的庫一起使用,您需要將focus元素設置為container值
new ClipboardJS('.btn', {
container: document.getElementById('modal')
});
- 更好的管理單頁面的DOM生命周期
var clipboard = new ClipboardJS('.btn');
clipboard.destroy();
兼容性

備註
如果需要支持更低版本的瀏覽器,可以參考官網的介紹,它能夠優雅的降級
提供Chrome和Firefox的擴展
一個瀏覽器擴展,為GitHub,MDN,Gist,StackOverflow,StackExchange,npm甚至Medium中的每個代碼塊添加“複製到剪貼板”按鈕。需要的可以私信或者前往擴展中心自行下載。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/222377.html
微信掃一掃
支付寶掃一掃