鼠标点击复制文本或文本的链接代码。
1、js代码
<script>
function copyLinkText(event) {
// 获取触发点击事件的元素
const link = event.target;
// 创建一个新的临时元素,并设置选区
const temp = document.createElement("span");
temp.innerHTML = link.textContent;
document.body.appendChild(temp);
// 选中文本
const range = document.createRange();
range.selectNodeContents(temp);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
// 复制到剪贴板
document.execCommand('copy');
// 清除选区并移除临时元素
selection.removeAllRanges();
document.body.removeChild(temp);
// 可以添加一些用户反馈,比如弹窗提示复制成功
alert("链接文本已复制到剪贴板!");
}
</script>2、html代码
<a href="https://www.qinghuahulian.com" onclick="copyLinkText(event)">点击复制这个链接文本</a> <a href="https://www.qinghuahulian.com"> <span class="copy-link-text">复制链接</span> </a>
我是有底线的
扫描二维码手机查看该文章
文章引用:https://www.qinghuahulian.com/news/webzhishi/1472.html




