<!-- 一个简单的小栗子 -->
<button class="copy-link"
data-fulllink="要被复制的内容在这里~">复制链接</button>
<!-- 空白节点,缓存数据,尽量使用下面的样式将该节点隐藏起来 -->
<div class="copy-area"></div>
<style>
.copy-area {
position: absolute;
z-index: -1;
width: 0;
height: 0;
opacity: 0;
}
</style>
<script>
function copyLink(event) {
let target = event.target;
let fullLink = target.getAttribute(\'data-fulllink\');
// 在页面上建一个空白节点,用来缓存要被复制的数据
let copyNode = document.querySelector(\'.copy-area\');
let range = document.createRange();
let selection = window.getSelection();
copyNode.innerHTML = fullLink;
range.selectNode(copyNode);
// 去除默认的选区对象
if (selection.rangeCount > 0) {
selection.removeAllRanges();
}
selection.addRange(range);
document.execCommand(\'copy\');
target.innerHTML = \'复制成功\';
}
document.querySelector(\'.copy-link\').onclick = copyLink;
</script>
相关文章: