直接上代码,通过触发 .copybtn 复制按钮,复制 .copytxt 的内容。
<div class="title">
<a class="button" href="javascript:history.back();">返 回</a>
作品编号:<span class="copytxt">PHP-001007</span>
<button class="copybtn">复 制</button>
</div>
<script>
function copyNo(event) {
const range = document.createRange();
range.selectNode(document.querySelector(".copytxt"));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('Copy');
alert("复制成功!");
}
document.querySelector(".copybtn").addEventListener('click', copyNo, false);
</script>
方法二:
function copyTxt() {
var copyText = document.getElementById("boomNo");
copyText.select();
copyText.setSelectionRange(0, 99999); /* 为移动设备设置 */
navigator.clipboard.writeText(copyText.value);
alert("复制成功");
}