document.execCommand文档 :https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
原代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text">
<table border="1px solid #ccc" cellspacing="0" cellpadding="0">
<tr>
<td>
<a>TAAAAA123456</a>
<button title="复制" type="button" onclick="copy(this)" style="width: 15px ;height: 15px">
<i class="fa fa-copy iconFunction"></i>
</button>
</td>
</tr>
<tr>
<td>
<a>TBBBBBB22222</a>
<button title="复制" type="button" onclick="copy(this)" style="width: 15px ;height: 15px">
<i style="text-align:right" class="fa fa-copy iconFunction"></i>
</button>
</td>
</tr>
<tr>
<td>
<a>TCCCCCCC33333</a>
<button title="复制" type="button" onclick="copy(this)" style="width: 15px ;height: 15px">
<i style="text-align:right" class="fa fa-copy iconFunction"></i>
</button>
</td>
</tr>
</table>
</body>
<script>
function copy(e) {
//找到当前点击的兄弟元素
var myelement = e.previousElementSibling.firstChild;
range = document.createRange();
range.selectNodeContents(myelement);
// 选中元素
window.getSelection().addRange(range);
try {
successful = document.execCommand('copy');
if (successful == true) {
alert(e.parentNode.innerText + ' 复制成功');
} else {
alert(e.parentNode.innerText + ' 复制失败');
}
} catch (err) {
alert('Oops, unable to copy');
}
// 移除选中的元素
window.getSelection().removeAllRanges();
}
</script>
</html>
运行效果 :
点击复制第一个,选中复制成功,点击复制第二个,未选中复制成功但是是第一个值,所以为题出现在选中内容上。
优化后的js
<script>
function copy(e) {
try {
//找到当前点击的兄弟元素
var myelement = e.previousElementSibling.firstChild;
range = document.createRange();
range.selectNodeContents(myelement);
// 移除选中的元素
window.getSelection().removeAllRanges();
// 选中元素
window.getSelection().addRange(range);
successful = document.execCommand('copy');
if (successful == true) {
alert(e.parentNode.innerText + ' 复制成功');
} else {
alert(e.parentNode.innerText + ' 复制失败');
}
} catch (err) {
alert('Oops, unable to copy');
}
}
</script>
最重要的一点是 window.getSelection().removeAllRanges();放的位置,放在选中之前,先撤销上一次的再重新选中,即可解决选中错误的问题。