1.clipboard.js 实现了纯 JavaScript (无 Flash)的浏览器内容复制到系统剪贴板的功能。可以在浏览器和 Node 环境中使用。支持 Chrome 42+、Firefox 41+、IE 9+、Opera 29+
cdn:<script src="https://cdn.bootcss.com/clipboard.js/1.6.1/clipboard.min.js"></script>
用法:
<script src="clipboard.min.js"></script> <textarea id="bar" cols="62" rows="5" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">脚本之家是国内专业的网站建设资源、脚本编程学习类网站,提供asp、php、asp.net、javascript、jquery、vbscript、dos批处理、网页制作、网络编程、网站建设等编程资料。</textarea> <!-- Trigger --> <button class="btn" data-clipboard-action="copy" data-clipboard-target="#bar"> Cut to clipboard </button> <script> var clipboard = new Clipboard('.btn'); clipboard.on('success', function(e) { console.info('Action:', e.action); console.info('Text:', e.text); console.info('Trigger:', e.trigger); alert("复制成功"); e.clearSelection(); }); clipboard.on('error', function(e) { console.error('Action:', e.action); console.error('Trigger:', e.trigger); }); </script>
2.react-copy-to-clipboard
安装:npm install --save react-copy-to-clipboard
用法:
import React from 'react'; import CopyToClipboard from 'react-copy-to-clipboard'; const App = React.createClass({ getInitialState() { return {value: '', copied: false}; }, render() { return ( <div> <input value={this.state.value} onChange={({target: {value}}) => this.setState({value, copied: false})} /> <CopyToClipboard text={this.state.value} onCopy={() => this.setState({copied: true})}> <span>Copy to clipboard with span</span> </CopyToClipboard> <CopyToClipboard text={this.state.value} onCopy={() => this.setState({copied: true})}> <button>Copy to clipboard with button</button> </CopyToClipboard> {this.state.copied ? <span style={{color: 'red'}}>Copied.</span> : null} </div> ); } }); React.render(<App />, document.body);