js實現復制粘貼的兩種方法
本文實例為大家分享了js實現復制粘貼的具體代碼,供大家參考,具體內容如下
一、前沿
界面需要復制功能,所以就寫了一個作為簡單記錄
二、方法、推薦第二種。
1、第一種方法
1)、通過 document.execCommand(’copy’)2)、前端代碼如下:
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>constructor-nodelist</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel='stylesheet' /></head><body><button onclick='copyText(’copy_file’)'>點我復制</button><a href='http://m.4tl426be.cn/bcjs/復制內容' ></a><script type='text/javascript' src='https://cdn.bootcss.com/sweetalert/1.1.3/sweetalert.min.js'></script><script>function copyText(str_file) { const btn = document.querySelector(’.’+str_file); var copy_val = document.getElementById(str_file) var copy_file = copy_val.getAttribute('href'); btn.addEventListener(’click’,() => { const input = document.createElement(’input’); document.body.appendChild(input); input.setAttribute(’value’, copy_file); input.select(); if (document.execCommand(’copy’)) { document.execCommand(’copy’); swal('復制成功!','success'); } document.body.removeChild(input); })}</script></body>
3)、總結:主要是通過 class和id 來復制 a標簽中的 href,把復制好的內容放到 生成的input標簽中,然后復制結束把 input標簽給remove,這個你復制內容自行發揮,和修改 js。4)、問題:第一次點擊不生效,需要點擊兩次,暫時不解決
2、第二種方法
1)、通過 ClipboardJS 來實現 內容的復制,推薦這個2)、git地址:clipboardjs3)、前端代碼如下:
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title> <!-- 請自行去git項目下載 js--> <script src='http://m.4tl426be.cn/bcjs/clipboard.min.js'></script> <link rel='stylesheet' /> <script type='text/javascript' src='https://cdn.bootcss.com/sweetalert/1.1.3/sweetalert.min.js'></script></head><body><button data-clipboard-text='str_555' onclick='copyText()'> <span>Copy</span></button></body></html><script>function copyText() { var btn = document.getElementById(’btn’); console.log(btn); var clipboard = new ClipboardJS(btn);<!-- var clipboard = new ClipboardJS(btn, {--><!-- container: document.getElementById(’btn’)--><!-- });--> 如果你的項目是 bootstrap框架,請使用這個 clipboard.on(’success’, function(e) { console.log(e); swal('復制成功!','success'); clipboard.destroy(); }); clipboard.on(’error’, function(e) { console.log(e); swal('復制失敗','error'); clipboard.destroy(); });}</script>
3)、總結:請一定要仔細閱讀 文檔。這個項目還是非常強大的,強烈推薦這個。
4)、問題:也是遇到了 第一次復制不生效的問題,暫時不解決了。
三、總結
1、都遇到了 第一次復制不生效的問題,后續解決把,都采用了 sweetalert 。2、個人都只在 谷歌和火狐瀏覽器實驗了,都可以用,如果其他瀏覽器版本不能用,請自行查閱其他文章,歡迎溝通、指正。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
