提示:
能运行博客中的代码哟~快来试试~
<script src="https://cdn.uv.cc/vue/2.6.10/vue.min.js"></script> <div id="app"> <div> <button @click="toClipBoard('something')">Copy to Clipboard</button> </div> </div> <script> new Vue({ el: '#app', methods: { toClipBoard(text) { // 创建一个临时的 textarea 元素 const textArea = document.createElement('textarea'); // 将要复制的文本设置到 textarea 中 textArea.value = text; // 将 textarea 元素添加到页面中(必须在 DOM 中) document.body.appendChild(textArea); // 选择 textarea 中的文本 textArea.select(); textArea.setSelectionRange(0, 99999); // 对于移动设备 try { // 执行复制命令 const successful = document.execCommand('copy'); if (successful) { console.log('Text successfully copied to clipboard!'); // 可以在这里添加提示用户复制成功的操作 } else { console.log('Failed to copy text.'); } } catch (err) { console.error('Oops, unable to copy', err); } // 复制后移除 textarea 元素 document.body.removeChild(textArea); } } }) </script>