js實(shí)現(xiàn)點(diǎn)擊按鈕復(fù)制文本功能,效果如下:
瀏覽器提供了 copy 命令 ,可以復(fù)制選中的內(nèi)容
document.execCommand("copy")
如果是輸入框,可以通過 select() 方法,選中輸入框的文本,然后調(diào)用 copy 命令,將文本復(fù)制到剪切板
但是 select() 方法只對(duì) <input> 和 <textarea> 有效,對(duì)于 <p> 就不好使
最后我的解決方案是,在頁(yè)面中添加一個(gè) <textarea>,然后把它隱藏掉
點(diǎn)擊按鈕的時(shí)候,先把 <textarea> 的 value 改為 <p> 的 innerText,然后復(fù)制 <textarea> 中的內(nèi)容
HTML 部分代碼
<style type="text/css"> .wrapper {position: relative;} #input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}</style><div class="wrapper"> <p id="text">我把你當(dāng)兄弟你卻想著復(fù)制我?</p> <textarea id="input">這是幕后黑手</textarea> <button onclick="copyText()">copy</button></div>
JS 部分代碼:
<script type="text/javascript"> function copyText() { var text = document.getElementById("text").innerText; var input = document.getElementById("input"); input.value = text; // 修改文本框的內(nèi)容 input.select(); // 選中文本 document.execCommand("copy"); // 執(zhí)行瀏覽器復(fù)制命令 alert("復(fù)制成功"); } </script>
經(jīng)過織夢(mèng)361模板網(wǎng)小編親測(cè),F(xiàn)irefox 48.0,Chrome 60.0,IE 8 都能用。
以上就是js實(shí)現(xiàn)點(diǎn)擊按鈕復(fù)制文本功能的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)和解決疑問有所幫助,也希望大家多多支持武林網(wǎng)。新聞熱點(diǎn)
疑難解答
圖片精選