
純javascript實(shí)現(xiàn)復(fù)制文本并提示復(fù)制成功兼容PC端,移動(dòng)端,適用所有瀏覽器,直接放項(xiàng)目就能用。
代碼如下:
<a onclick="copyTxt('這是要復(fù)制的內(nèi)容')">點(diǎn)擊復(fù)制</a>
js:
<script>
//原生js實(shí)現(xiàn)復(fù)制內(nèi)容到剪切板,兼容pc、移動(dòng)端(支持Safari瀏覽器)
function copyTxt(text){
if(typeof document.execCommand!=="function"){
alert("復(fù)制失敗,請長按復(fù)制");
return;
}
var dom = document.createElement("textarea");
dom.value = text;
dom.setAttribute('style', 'display: block;width: 1px;height: 1px;');
document.body.appendChild(dom);
dom.select();
var result = document.execCommand('copy');
document.body.removeChild(dom);
if (result) {
alert("復(fù)制成功");
return;
}
if(typeof document.createRange!=="function"){
alert("復(fù)制失敗,請長按復(fù)制");
return;
}
var range = document.createRange();
var div=document.createElement('div');
div.innerHTML=text;
div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;');
document.body.appendChild(div);
range.selectNode(div);
const selection = window.getSelection();
if (selection.rangeCount > 0){
selection.removeAllRanges();
}
selection.addRange(range);
document.execCommand('copy');
alert("復(fù)制成功")
}
</script>
您發(fā)布的評論即表示同意遵守以下條款:
一、不得利用本站危害國家安全、泄露國家秘密,不得侵犯國家、社會(huì)、集體和公民的合法權(quán)益;
二、不得發(fā)布國家法律、法規(guī)明令禁止的內(nèi)容;互相尊重,對自己在本站的言論和行為負(fù)責(zé);
三、本站對您所發(fā)布內(nèi)容擁有處置權(quán)。