1、在做點擊按鈕復制功能時遇到了小小的卡頓,此處遇到了兩種系統手機的兼容性 / 復制后會對文本進行選中 / 輸入法彈出 等。現將方法進行總結,如下代碼很好對解決了以上問題,適用性強。
2、在文本此處使用p標簽或者div標簽都可
<div class="copy-font">
<div class="uuid-code" id="content">saidfh3is21111h</div>
<button class="btn-copy" id="copyBT">復制</button>
</div>
3、采用對原生js,首先對需要復制對文本進行選中節點,檢測設備中是否含有其他的復制文本緩存,進行清除。
將需要復制的文本進行賦值,並調用dom對象的copy功能,返回復制成功提示。
<script type="text/javascript">
function copyArticle(event) {
const range = document.createRange();
range.selectNode(document.getElementById('content'));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("復制成功!");
}
document.getElementById('copyBT').addEventListener('click', copyArticle, false);
</script>