<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
* {
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<table border="1" cellpadding="0">
<tr>
<th>
<button id="copy">复制</button>
</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
<tr>
<td class="shuzi">aaaaaaaaaaaaaa</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td class="shuzi">bbbbbbbbbbbbb</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td class="shuzi">ccccccccccc</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td class="shuzi">dddd</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
</body>
<script src="jquery.min.js"></script>
<script type="text/javascript">
// 选中一列
content = "";
$("table tr td,table tr th").on("click", function () {
var index = $(this).index();
content = "";
Array.from($("table tr td")).forEach(item => {
if (item.cellIndex == index) {
content += item.innerHTML + "
";
}
});
var flag = copyText(content);
alert(flag ? "复制成功!" : "复制失败!");
});
/*
$("#copy").click(function () {
var arr = $(".shuzi");
var content ="";
Array.from(arr).forEach(item => {
content += item.innerHTML+"
";
});
var flag = copyText(content);
alert(flag ? "复制成功!" : "复制失败!");
});
*/
function copyText(text) {
var textarea = document.createElement("textarea");//创建input对象
var currentFocus = document.activeElement;//当前获得焦点的元素
document.body.appendChild(textarea);//添加元素
// 给表单赋值
textarea.value = text;
// 判断光标是否在第一位置
textarea.focus();
if (textarea.setSelectionRange)
textarea.setSelectionRange(0, textarea.value.length);//获取光标起始位置到结束位置
else
textarea.select();
try {
var flag = document.execCommand("copy");//执行复制
} catch (eo) {
var flag = false;
}
document.body.removeChild(textarea);//删除元素
currentFocus.focus();
return flag;
}
</script>
</html>