我想选择点击td的innerHTML,这样用户就可以按ctrl + C来复制内容。
我尝试了很多组合,但我找不到办法。然而,它使用简单的document.getElementById(id).select();
添加焦点不会影响任何内容,而.select()发送和错误:
document.getElementById(...)。select不是函数
那么我怎么能用td元素呢? 如果它不在IE上工作,我不介意。
或者,如果可能,直接复制文本。
答案 0 :(得分:8)
点击后,您可以选择td
的文字。
$("td").click(function(){
var range = document.createRange();
range.selectNodeContents(this);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
});
table, tr, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Column1</td>
<td>Column2</td>
<td>Column3</td>
</tr>
<tr>
<td>Column1</td>
<td>Column2</td>
<td>Column3</td>
</tr>
</table>
答案 1 :(得分:4)
同样复制并不难。我使用这个功能,这也适用于其他浏览器,而不仅仅是IE(来源未知)。
https://jsfiddle.net/5bhkydq1/
html代码
<div>
Click me to copy!
</div>
javascript和jquery
$('div').click(function(){
copyTextToClipboard($(this).html());
});
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
// Avoid flash of white box if rendered for any reason.
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
答案 2 :(得分:0)
尝试一下:
$("td").click(function (e) {
var clickedCell = $(e.target).closest("td");
navigator.clipboard.writeText(clickedCell.text());
});
它将点击的单元格文本写入浏览器剪贴板,对我有用!
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText