方法一: 使用 js 实现
1 function copyToClipboard (text) { 2 if(text.indexOf('-') !== -1) { 3 let arr = text.split('-'); 4 text = arr[0] + arr[1]; 5 } 6 var textArea = document.createElement("textarea"); 7 textArea.style.position = 'fixed'; 8 textArea.style.top = '0'; 9 textArea.style.left = '0'; 10 textArea.style.width = '2em'; 11 textArea.style.height = '2em'; 12 textArea.style.padding = '0'; 13 textArea.style.border = 'none'; 14 textArea.style.outline = 'none'; 15 textArea.style.boxShadow = 'none'; 16 textArea.style.background = 'transparent'; 17 textArea.value = text; 18 document.body.appendChild(textArea); 19 textArea.select(); 20 21 try { 22 var successful = document.execCommand('copy'); 23 var msg = successful ? '成功复制到剪贴板' : '该浏览器不支持点击复制到剪贴板'; 24 alert(msg); 25 } catch (err) { 26 alert('该浏览器不支持点击复制到剪贴板'); 27 } 28 29 document.body.removeChild(textArea); 30 }
方法二:使用clipboard.min.js 实现
1: 在vue项目中,首先引入clipboard.min.js 类库
2: 利用vue钩子在页面加载完成后初始化clipboard对象
1 mounted(){ 2 new Clipboard($(this.$el).find('.btn-copy')[0]); 3 new Clipboard($(this.$el).find('.btn-copy')[1]); 4 }
3:html页面的复制按钮添加属性
span.btn-copy.copy( @click="copyclipboard",data-clipboard-text="这里面是复制的内容,可以使用变量代替") 点击复制
在非vue项目中也是一样,引入类库后初始化Clipboard对象就可以使用了
下面贴出一段使用案例源码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>target-div</title> </head> <body> <!-- 1. Define some markup --> <div>hello</div> <button class="btn" data-clipboard-action="copy" data-clipboard-target="div">Copy</button> <!-- 2. Include library --> <script src="../dist/clipboard.min.js"></script> <!-- 3. Instantiate clipboard --> <script> var clipboard = new Clipboard('.btn'); clipboard.on('success', function(e) { console.log(e); }); clipboard.on('error', function(e) { console.log(e); }); </script> </body> </html>
可以参考github上的源码,写的很清晰
https://github.com/zenorocha/clipboard.js/