我想知道是否有人知道如何使用js选择整个表格,以便用户可以右击选择,将其复制到剪贴板,然后将其粘贴到Excel上。如果您手动选择该表,该过程将完美运行。但有时,如果桌子高度比屏幕大几倍,拖动鼠标选择它就会变得单调乏味。因此,我想让用户可以单击“选择整个表”按钮,然后所有内容都准备好被复制。
有什么想法吗?
发布于 2017-02-14 02:29:30
只是为了使Tim Down提出的代码更加完整,允许将选定的内容自动复制到剪贴板:
<script type="text/javascript">
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
document.execCommand("copy");
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand("Copy");
}
}
</script>
<table id="tableId">
<thead>
<tr><th>Heading</th><th>Heading</th></tr>
</thead>
<tbody>
<tr><td>cell</td><td>cell</td></tr>
</tbody>
</table>
<input type="button" value="select table"
onclick="selectElementContents( document.getElementById('tableId') );">
发布于 2012-09-05 16:28:59
我最终通过使用以下脚本使其在IE9中正常工作
注意:它在html表格上不起作用。一定是静脉注射。因此,只需在需要选择的表周围放置一个包装器DIV!
首先,我稍微修改了一下HTML按钮代码:
<input type="button" value="Mark table" onclick="SelectContent('table1');">
然后将javascript更改为:
function SelectContent (el) {
var elemToSelect = document.getElementById (el);
if (window.getSelection) { // all browsers, except IE before version 9
var selection = window.getSelection ();
var rangeToSelect = document.createRange ();
rangeToSelect.selectNodeContents (elemToSelect);
selection.removeAllRanges ();
selection.addRange (rangeToSelect);
}
else // Internet Explorer before version 9
if (document.body.createTextRange) { // Internet Explorer
var rangeToSelect = document.body.createTextRange ();
rangeToSelect.moveToElementText (elemToSelect);
rangeToSelect.select ();
}
else if (document.createRange && window.getSelection) {
range = document.createRange();
range.selectNodeContents(el);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
发布于 2018-07-19 21:38:30
这是我用过的。它还创建了复制命令,因此您所要做的就是在要将其放入其中的文档中使用粘贴命令。基本上,您将想要复制的内容包装在一个div中,使用innerHTML抓取它,然后将其复制到剪贴板。我没有在所有的浏览器上测试它,但它在Chrome,Safari,Firefox上都能工作。
<div id="copycontent">
<table>
</table>
</div>
<input type="button" value="Mark table" onclick="SelectContent('copycontent');">
<script type="text/javascript">
function SelectContent (el) {
var aux = document.createElement("div");
aux.setAttribute("contentEditable", true);
aux.innerHTML = document.getElementById("main").innerHTML;
aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
document.body.appendChild(aux);
aux.focus();
document.execCommand("copy");
document.body.removeChild(aux);
}
</script>
https://stackoverflow.com/questions/2044616
复制相似问题