



// 示例:使用隐藏textarea实现表格复制 function copytableToClipboard(tableId) { const table = document.getElementById(tableId); if (!table) { console.error('Table not found with ID:', tableId); return; } let data = ''; const rows = table.queryselectorAll('tr'); rows.forEach(row => { const cols = row.querySelectorAll('td, th'); const rowData = []; cols.forEach(col => { // 简单处理,获取文本内容,去除多余空白 rowData.push(col.innerText.trim().replace(/s+/g, ' ')); }); data += rowData.join('t') + 'n'; }); // 创建一个临时的textarea元素 const tempTextArea = document.createElement('textarea'); tempTextArea.value = data; // 隐藏textarea,防止它影响页面布局和用户体验 tempTextArea.style.position = 'absolute'; tempTextArea.style.left = '-9999px'; document.body.appendChild(tempTextArea); // 选中textarea内容并执行复制命令 tempTextArea.select(); try { const successful = document.execCommand('copy'); const msg = successful ? '表格数据已复制!' : '复制失败,请手动复制。'; console.log(msg); // 可以在这里给用户一个短暂的提示 alert(msg); } catch (err) { console.error('复制命令执行失败:', err); alert('复制失败,您的浏览器可能不支持此操作,请手动复制。'); } finally { // 复制完成后移除textarea document.body.removeChild(tempTextArea); } } // 示例:使用Clipboard API (更现代) async function copyTableToClipboardModern(tableId) { const table = document.getElementById(tableId); if (!table) { console.error('Table not found with ID:', tableId); return; } let data = ''; const rows = table.querySelectorAll('tr'); rows.forEach(row => { const cols = row.querySelectorAll('td, th'); const rowData = []; cols.forEach(col => { rowData.push(col.innerText.trim().replace(/s+/g, ' ')); }); data += rowData.join('t') + 'n'; }); try { await navigator.clipboard.writeText(data); console.log('表格数据已通过Clipboard API复制!'); alert('表格数据已复制!'); } catch (err) { console.error('Clipboard API 复制失败:', err); alert('复制失败,您的浏览器可能不支持或权限不足。请确保在httpS环境下且有用户手势触发。'); } } // 假设你的html表格ID是 'myTable' // <table id="myTable">...</table> // <button onclick="copyTableToClipboard('myTable')">复制表格数据 (兼容)</button> // <button onclick="copyTableToClipboardModern('myTable')">复制表格数据 (现代)</button>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END