使用JavaScript将表格行复制到剪贴板

时间:2018-09-05 18:00:42

标签: javascript copy clipboard

使用javascript复制到剪贴板,然后将其粘贴到适用于表格的excel /电子表格中,但不适用于表格行。对于表格行,它确实复制了文本,但不是将其粘贴在单独的行中,而是粘贴为一行,作为单个字符串。

<script>
function copyText(el) {
  let elem = document.getElementById(el);
  let body = document.body, range, sel;

  if(document.createRange && window.getSelection) {
    range = document.createRange();
    sel = window.getSelection();
    sel.removeAllRanges();
    try {
      range.selectNodeContents(elem);
      sel.addRange(range)
    } catch (e) {
       range.selectNode(elem);
       sel.addRange(range)
    }
  } else if (body.createTextRange) {
    range = body.createTextRange();
    range.moveToElementText(elem);
    range.select();
  }
  document.execCommand('copy');
}
</script>

<table id="table">
  <tr>
    <td>Data #1</td>
    <td>Data #2</td>
  </tr>
  <tr id="trow">
    <td>Data #3</td>
    <td>Data #4</td>
  </tr>
</table>

<button onclick="copyText('table')">Copy Table</button>
<button onclick="copyText('trow')">Copy Row</button>

0 个答案:

没有答案