JQuery - 如何在表中的每个td元素中触发用户选择:文本?

问题描述 投票:0回答:2

我想突出显示表格中的所有文字。我把user-select:text放在我的CSS中,我能够手动突出显示td内的文本。

td{
    user-select: text;
}

但是如何自动突出显示呢?

PS:

  • 表格的每个单元格中只有文本,没有图像等。
  • 我希望能够复制表格中的所有文字。
jquery html html-table
2个回答
3
投票

window.getSelection().selectAllChildren( document.getElementById('markME') );
<table id="markME">
<tbody>
  <tr>
    <td>1231</td>
    <td>1231</td>
    <td>1231</td>
    <td>1231</td>
    <td>1231</td>    
  </tr>
</tbody>
</table>

Reference of Selection


1
投票

我希望能够复制表格中的所有文字。

我有一个,你也想自动复制到表格内容的剪贴板,如果是这样你可以用以下内容;

$('#btn-copy').on('click', function(){
  
  //(1) - Get the html code of the table and insert into variable contentToCopy
  var contentToCopy = $('#your-table')[0].outerHTML;

//(2) - insert the html code into our hidden TextArea, notice I used html instead of val to preserve the html code
$('#hiddenTextarea').html(contentToCopy);

//(3) - by using select, we hightlight all the value inside our hidden TextArea
$('#hiddenTextarea').select();
  
  if(document.execCommand('copy')){ //finally copy the value of our hidden TextArea into clipboard by using function document.execCommand('copy')
	  alert('Copied! You may now paste it to excel, word, etc.');   		
	}
});
/*Optional, I just want to make content clear*/
table {
  border-collapse: collapse;
}
table, th, td {
  border: 1px solid #DDD;
  padding: 5px;
}

/*We hide the Textarea by using absolute and position it to the left by negative 1000*/
#hiddenTextarea{
  position: absolute;
  left: -1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="your-table">
<tbody>
  <tr>
    <td>Content 1</td>
    <td>Content 2</td>
    <td>Content 3</td>    
  </tr>
</tbody>
</table>

<textarea id="hiddenTextarea"></textarea>

<br/>
<button id="btn-copy">Copy to Clipboard</button>
© www.soinside.com 2019 - 2024. All rights reserved.