使用clipboard實現前端頁面複製到粘貼板的功能

最近公司須要作一個js實現複製的功能,原本覺得會是很簡單兩三行js代碼的事,後來發現網上說的那些原生js實現複製的方法不少瀏覽器由於安全的緣由都不支持了,嘗試了很長時間,仍是死心了,決定使用第三方的js庫。
最早看了利用flash技術的ZeroClipboard,體積龐大很差用放棄了。
最終選擇了不依賴flash輕量級js庫clipBoard,官網地址https://clipboardjs.com/瀏覽器

使用很簡單
第一步:引入js庫 <script src="../dist/clipboard.min.js"></script>
第二步:定義標籤(通常是觸發複製的按鈕)<button class="btn">Copy</button>
第三步:實例化clipboard,調用構造函數var clipboard = new Clipboard('.btn');安全

結合官方給的demo看一下幾種場景函數

1.從變量賦值內容到剪貼板

var clipboard = new Clipboard('.btn', {
        text: function() {
            return 'to be or not to be';
        }
    });

點擊button,'to be or not to be'會粘貼到剪貼板code

2.複製頁面中div/input/textarea的內容

第一種方法構造函數裏定義targetip

<div>hello</div>
var clipboard = new Clipboard('.btn', {
        target: function() {
            return document.querySelector('div');
        }
    });

點擊button,'hello'會粘貼到剪貼板get

還有第二種方法在button裏定義屬性data-clipboard-target和data-clipboard-actioninput

<div>hello</div>
<button class="btn" data-clipboard-action="copy" data-clipboard-target="div">Copy</button>
var clipboard = new Clipboard('.btn');

一樣的,點擊button,'hello'會粘貼到剪貼板回調函數

input和textarea用法相似flash

<input id="foo" type="text" value="hello">
<button class="btn" data-clipboard-action="copy" data-clipboard-target="#foo">Copy</button>
<textarea id="bar">hello</textarea>
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">Cut</button>

最重要的一點clipboard還定義了複製成功/失敗的回調函數,方便咱們去處理後面的邏輯io

clipboard.on('success', function(e) {
        console.log(e);
    });

clipboard.on('error', function(e) {
        console.log(e);
    });

完。

相關文章
相關標籤/搜索