[英]Copy HTML table structure to clipboard
我只是在尋求建議。 我一直在互聯網上尋找有關如何將帶有文本的HTML表結構復制到剪貼板的可能解決方案,但到目前為止還沒有那么幸運。
目前,我擁有的是一個簡單的數據表,用戶需要使用Outlook以及在復制/粘貼數據時將其復制到電子郵件中。 手動將其粘貼到Outlook中將顯示表結構及其文本正確呈現。 唯一的問題是,有時用戶可能有多個大表,有時有時笨拙地同時復制和向下滾動以到達頁面底部。
因此,我希望獲得一個簡單的按鈕,該按鈕本質上將自動執行此操作。 因此,我正在尋找可以找到我的主要div容器並將其中的所有表結構和文本復制到用戶剪貼板的東西。 我發現最受歡迎的解決方案稱為ZeroClipboard,但是它僅復制文本,而不復制文本的實際HTML表結構。
有誰知道這是否可以通過Jquery或其他插件來完成? 我將不勝感激對此的任何建議。
我認為您無法通過按鈕觸發復制事件,但是建議采取一種解決方法:剪貼板API允許您在復制事件上設置自定義數據。 因此,您可以做的是偵聽表上的copy
事件,然后以文本形式發送HTML
。 因此,從表中觸發復制事件的用戶將在剪貼板中獲取HTML
(或所需的任何文本)。
在下面的代碼段示例中,選擇一些文本並將其復制:
document.getElementById('sample').addEventListener('copy', function (e) { var html_data = document.getElementById('sample').innerHTML; document.getElementById('result').textContent = html_data; e.clipboardData.setData('text/plain', html_data); e.preventDefault(); });
span { color: red; }
<div id='sample'> <div style="padding-bottom: 5px;">Select some of this text and copy it to clipboard using ctrl+c or right-click+copy.</div> </div> <div >The content of the clipboard is: <span id="result"></span></div>
剪貼板API的文檔: http : //www.w3.org/TR/clipboard-apis/
並且來自caniuse: http ://caniuse.com/#feat=clipboard
您也可以使用execCommand
方法。
例:
const btnCopyText = document.querySelector('#btn-copy-text');
const btnCopyTable = document.querySelector('#btn-copy-table');
const elText = document.querySelector('p');
const elTable = document.querySelector('table');
const copyEl = (elToBeCopied) => {
let range, sel;
// Ensure that range and selection are supported by the browsers
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
// unselect any element in the page
sel.removeAllRanges();
try {
range.selectNodeContents(elToBeCopied);
sel.addRange(range);
} catch (e) {
range.selectNode(elToBeCopied);
sel.addRange(range);
}
document.execCommand('copy');
}
sel.removeAllRanges();
console.log('Element Copied! Paste it in a file')
};
btnCopyText.addEventListener('click', () => copyEl(elText));
btnCopyTable.addEventListener('click', () => copyEl(elTable));
HTML:
<div>
<button id="btn-copy-text">Copy this text 👇🏻</button>
<p id="text-to-copied">Text to be copied</p>
</div>
<div class="table-container">
<button id="btn-copy-table">Copy Table</button>
<table id="table-to-copied" border="1">
<tr>
<td>col1 </td>
<td>col2 </td>
</tr>
<tr>
<td>col1 </td>
<td>col2 </td>
</tr>
<tr>
<td>col1 </td>
<td>col2 </td>
</tr>
<tr>
<td>col1 </td>
<td>col2 </td>
</tr>
<tr>
<td>col1 </td>
<td>col2 </td>
</tr>
<tr>
<td>col1 </td>
<td>col2 </td>
</tr>
</table>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.