原生js實現(xiàn)點(diǎn)擊按鈕復(fù)制內(nèi)容到剪切板
更新時間:2020年11月19日 11:05:38 作者:weixin_44953227
這篇文章主要為大家詳細(xì)介紹了原生js實現(xiàn)點(diǎn)擊按鈕復(fù)制內(nèi)容到剪切板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js點(diǎn)擊按鈕復(fù)制內(nèi)容到剪切板的具體代碼,供大家參考,具體內(nèi)容如下
效果圖
上代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> .divBox { width: 500px; margin: 100px auto; display: flex; } .popupStyle { display: none; width: 160px; background-color: rgb(85, 85, 85); color: aqua; text-align: center; border-radius: 6px; padding: 8px 0; position: fixed; z-index: 1; top: 2%; left: 50%; margin-left: -80px; } </style> <body> <div class="divBox"> <div id="div">這是要復(fù)制的div內(nèi)容</div> <a href="#" onclick="handleDivCopy()">點(diǎn)擊復(fù)制</a> </div> <div class="divBox"> <textarea id="textarea">Hello,World</textarea> <a href="#" onclick="handleCopy()">點(diǎn)擊復(fù)制</a> </div> <script> // 復(fù)制 div 內(nèi)容 function handleDivCopy() { const div = document.getElementById("div"); const input = document.createElement("input"); document.body.appendChild(input); input.value = div.innerText; input.select(); try { if (document.execCommand("copy", false)) { handleDomMsg("div 內(nèi)容復(fù)制成功"); } else { handleDomMsg("div 內(nèi)容復(fù)制失敗"); } } catch (error) { console.log(error, "error") } finally { input.remove(); } }; // 復(fù)制輸入框內(nèi)容 function handleCopy() { const textarea = document.getElementById("textarea"); textarea.select(); try { if (document.execCommand("copy", false)) { handleDomMsg("輸入框內(nèi)容復(fù)制成功"); } else { handleDomMsg("輸入框內(nèi)容復(fù)制失敗"); } } catch (error) { console.log(error, "error") } }; // DOM 彈窗 function handleDomMsg(message) { const div = document.createElement("div"); document.body.appendChild(div); div.innerHTML = message || "this is a Message"; div.className = "popupStyle"; div.style.display = "block"; setTimeout(() => { div.remove(); }, 1000); } </script> </body> </html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- js實現(xiàn)點(diǎn)擊按鈕復(fù)制文本功能
- js實現(xiàn)點(diǎn)擊復(fù)制當(dāng)前文本到剪貼板功能(兼容所有瀏覽器)
- js實現(xiàn)點(diǎn)擊后將文字或圖片復(fù)制到剪貼板的方法
- JS簡單實現(xiàn)點(diǎn)擊復(fù)制鏈接的方法
- 用 javascript 實現(xiàn)的點(diǎn)擊復(fù)制代碼
- JavaScript實現(xiàn)點(diǎn)擊按鈕就復(fù)制當(dāng)前網(wǎng)址
- 點(diǎn)擊進(jìn)行復(fù)制的JS代碼實例
- JavaScript 點(diǎn)擊觸發(fā)復(fù)制功能實例詳解
- JavaScript實現(xiàn)點(diǎn)擊復(fù)制功能具體代碼(JS訪問剪貼板相關(guān))
相關(guān)文章
詳解Javascript中document.execCommand()的用法以及指令參數(shù)列表
execCommand方法是執(zhí)行一個對當(dāng)前文檔,當(dāng)前選擇或者給出范圍的命令。在HTML5中,execCommand可以通過JavaScript代碼來調(diào)用,使得開發(fā)者可以在網(wǎng)頁中實現(xiàn)一些復(fù)雜的文本操作。在HTML編輯器中這個命令用得很多,酷炫的強(qiáng)大功能。2023-07-07Spring Boot+AngularJS+BootStrap實現(xiàn)進(jìn)度條示例代碼
一般上傳文件時都需要進(jìn)度條,本篇文章主要介紹了Spring Boot+AngularJS+BootStrap實現(xiàn)進(jìn)度條示例代碼,有興趣的可以了解一下。2017-03-03150行代碼帶你實現(xiàn)微信小程序中的數(shù)據(jù)偵聽
在這篇文章中, 我將用150行代碼, 手把手帶你打造一個小程序也可以使用的偵聽器,感興趣的朋友跟隨小編一起看看吧2019-05-05