拷貝功能
場景:
點選拷貝按鈕時,拷貝表格内容實作可以複制,為保證樣式好看一個tr一行資料。
實作:
<button class="copy">拷貝</button>
<table class="table">
<thead>
<tr>
<th>快遞單号</th>
<th>訂單号</th>
<th>金額</th>
</tr>
</thead>
<tbody class="tbody">
<tr>
<td>650663245490481661</td>
<td>1000111100020445281</td>
<td>1000.00</td>
</tr>
<tr>
<td>590663245494572661</td>
<td>1000111100020445281</td>
<td>1000.00</td>
</tr>
<tr>
<td>590663245494572661</td>
<td>1000111100020445281</td>
<td>1000.00</td>
</tr>
</tbody>
</table>
// 樣式
<style>
table,
th,
td {
border: 1px solid #ccc;
}
table {
border-collapse: collapse;
width: 600px;
}
td {
text-align: center;
}
button {
margin: 20px 0;
}
</style>
// 功能
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
$('button').click(function() {
let tbody = $('.tbody')[0].innerText
let tbodyData = tbody.replace(/ +/g, ',').split(',')
let str = ''
for(let i = 0; i<tbodyData.length; i++ ) {
console.log('i', i, tbodyData[i]);
if (i%3 == 2) {
str = str + tbodyData[i] + '\n'
} else {
str = str + tbodyData[i] + ' '
}
}
// console.log('str', str)
let oInput = document.createElement("textarea"); // 如果寫input不會識别 \n 不會換行
oInput.style.border = "0 none";
oInput.style.color = "transparent";
oInput.value = str;
document.body.appendChild(oInput);
oInput.select(); // 選擇對象
document.execCommand("Copy"); // 執行浏覽器複制指令
oInput.parentNode.removeChild(oInput)
$('.showText')[0].innerText = str
})
</script>
效果:
在進行複制即可
650663245490481661 1000111100020445281 1000.00
590663245494572661 1000111100020445281 1000.00
590663245494572661 1000111100020445281 1000.00