最近開發遇到一個需求, 要把一串文字複製到剪貼板, 而後就看了下 github, 發現了一個 star 2W 多的庫 clipboard
, 想都沒想就拉來用了, 結果發現這貨真特麼不是通常的難用, 特別是和 react 或者 vue 綁定的時候, 簡直不想吐槽.vue
因此造了個用起來更舒服, 而且體積更小, 沒有依賴的庫來節省時間.react
這個庫的名字叫 iclipboard
.git
你能夠在 npm 上找到它: http://npmjs.com/package/icli....github
或者在 GitHub 上查看源代碼: https://github.com/acrazing/i....npm
安裝: npm 或者 yarn 均可以瀏覽器
npm install -S iclipboard yarn add iclipboard
使用: 這個庫只提供了一個接口: copy(text): boolean
, 使用的時候只須要調用這個函數就 ok:bash
import { copy } from 'iclipboard' copy('你想要的字符串')
可是須要注意: 複製粘貼操做瀏覽器限定只能是在用戶交互的時候發生, 所以必定是在某個元素的click
或者其它事件回調中同步調用, 因此完整的代碼看起來大概長成這樣子:函數
import { copy } from 'iclipboard' const button = document.getElementById('button-id') button.addEventListener('click', () => { if(copy('Hello world!')) { alert('複製成功') } else { alert('複製失敗') } })
在 React 中調用也是同樣:this
import React from 'react' import { copy } from 'iclipboard' class App extends React.Component { handleClick = () => { if(copy('Hello world!')) { alert('複製成功') } else { alert('複製失敗') } } render() { return <button onClick={this.handleClick}>複製</button> } }