<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击复制按钮复制指定内容</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<table id="data">
<tr>
<td class="copyable"> 姓名:</td>
<td class="copyable">张三</td>
</tr>
<tr>
<td class="copyable"> 年龄:</td>
<td class="copyable">18</td>
</tr>
<tr>
<td class="copyable"> 性别:</td>
<td class="copyable">男</td>
</tr>
</table>
<br>
<button id="copy">copy</button>
<br>
<div id="copy-temp"></div>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#copy").click(function () {
var $o = $("<textarea rows='10' cols='50'>");
$o.val($("#data .copyable").text())//填充要复制的文字
$("#copy-temp").append($o)
if (copy($o[0])) {
$o.remove()
alert("复制成功!");
}else{
alert("复制失败,请手动复制");
}
})
function copy(obj) {
obj.select();
try {
if (document.execCommand('copy', false, null)) {
document.execCommand("Copy");
return true;
}
} catch (err) {
}
return false;
}
</script>