JS代碼實(shí)現(xiàn)復(fù)制功能

一、實(shí)現(xiàn)原理

瀏覽器提供了copy命令,將選中內(nèi)容復(fù)制到剪切板

document.exeCommand("Copy");


二、實(shí)例

select()方法只對(duì)<input>和<textarea>有效

所以,如果要對(duì)普通文本進(jìn)行復(fù)制,再將文本內(nèi)容復(fù)制給<input>或<textarea>,復(fù)制成功后將該標(biāo)簽隱藏,從而實(shí)現(xiàn)復(fù)制

<script type="text/javascript">

function copytxt() {

????var txt = document.getElementById("copy").innerText; //獲取需要復(fù)制內(nèi)容

????var Input = document.createElement("input"); //使用createElement()創(chuàng)建 input 元素? ?

????Input.value = txt; //將內(nèi)容賦值給 input 的 value

????document.body.appendChild(Input); //添加 input 元素

????Input.select(); // 選擇對(duì)象? ?

????document.execCommand("Copy"); // 執(zhí)行瀏覽器復(fù)制命令

????Input.style.display = "none"; //隱藏 input 元素alert('復(fù)制成功');

}

</script>

<!-- 將onClick="copytxt()"時(shí)間添加到文本所在的DOM,可實(shí)現(xiàn)點(diǎn)擊文字復(fù)制 -->

<div id="copy">12345678</div>

<!-- 本案例為點(diǎn)擊按鈕復(fù)制 -->

<input type="button" onClick="copytxt()" value="點(diǎn)擊復(fù)制" />

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容