直接上代码,通过触发 .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("复制成功");
}

本文介绍了一种使用JavaScript实现的一键复制功能,通过触发复制按钮,可以轻松复制指定文本内容。方法包括利用document的方法选择和复制文本,适用于各种浏览器环境。
953

被折叠的 条评论
为什么被折叠?



