一、實(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ù)制" />