
純javascript實現復制文本并提示復制成功兼容PC端,移動端,適用所有瀏覽器,直接放項目就能用。
代碼如下:
<a onclick="copyTxt('這是要復制的內容')">點擊復制</a>
js:
<script>
//原生js實現復制內容到剪切板,兼容pc、移動端(支持Safari瀏覽器)
function copyTxt(text){
if(typeof document.execCommand!=="function"){
alert("復制失敗,請長按復制");
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("復制成功");
return;
}
if(typeof document.createRange!=="function"){
alert("復制失敗,請長按復制");
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("復制成功")
}
</script>
您發布的評論即表示同意遵守以下條款:
一、不得利用本站危害國家安全、泄露國家秘密,不得侵犯國家、社會、集體和公民的合法權益;
二、不得發布國家法律、法規明令禁止的內容;互相尊重,對自己在本站的言論和行為負責;
三、本站對您所發布內容擁有處置權。