一、js代碼
function CopyID(id){
const range = document.createRange();????//創(chuàng)建range對(duì)象
range.selectNode(document.getElementById(id));? ? //選取元素節(jié)點(diǎn)
const selection = window.getSelection();? ? //創(chuàng)建 selection對(duì)象
if(selection.rangeCount > 0) {? ? ?
//返回選區(qū)(selection)中range對(duì)象數(shù)量的只讀屬性,注:在網(wǎng)頁(yè)使用者點(diǎn)擊一個(gè)加載完畢的新打開的頁(yè)面之前,rangeCount的值是0。在使用者點(diǎn)擊頁(yè)面之后,rangeCount的值變?yōu)?,即使并沒有可視的選區(qū)(selection)。使用者一般情況下在一次只能選擇一個(gè)range?,所以通常情況下rangeCount屬性的值總為1。腳本(如javascript)可以使選區(qū)包含多個(gè)range。
????selection.removeAllRanges();
// Selection.removeAllRanges()方法會(huì)從當(dāng)前selection對(duì)象中移除所有的range對(duì)象,取消所有的選擇只?留下anchorNode?和focusNode屬性并將其設(shè)置為null。
}
selection.addRange(range);????//將range對(duì)象添加到selection選取當(dāng)中
document.execCommand('copy');? ? //復(fù)制選中的文字到剪貼板
}
二、使用方法
<span id="copy" onClick="CopyID('copy')">點(diǎn)擊復(fù)制</span>