使用 Javascript 选择一个完整的表格(要复制到剪贴板) [英] Select a complete table with Javascript (to be copied to clipboard)

查看:22
本文介绍了使用 Javascript 选择一个完整的表格(要复制到剪贴板)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道如何使用js选择完整的表格,以便用户可以右键单击选择,将其复制到剪贴板,然后将其粘贴到Excel上.如果您手动选择表格,该过程将完美运行.但有时,如果表格高度比屏幕大几倍,拖动鼠标选择它会变得乏味.所以,我想让用户有可能点击选择整个表格"按钮,一切都准备好被复制.

I was wondering if anybody knows how to select using js the complete table, so that the user can right-click on the selection, copy it to the clipboard and then paste it on Excel. If you select the table manually, the process works perfectly. But sometimes, if the table height is a few times larger than the screen, selecting it dragging the mouse gets tedious. So, I want to give the users the possibility to click on a "select the whole table" button and everything gets ready to be copied.

有什么想法吗?

推荐答案

是的.这不是太棘手,以下将适用于所有主流浏览器(包括 IE 6,甚至 5):

Yes. It's not too tricky, and the following will work in all mainstream browsers (including IE 6, and indeed 5):

(2012 年 9 月 7 日在 Jukka Korpela 的评论指出之前的版本在 IE 9 标准模式下无法运行后更新)

演示:http://jsfiddle.net/timdown/hGkGp/749/

代码:

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);
		}
	} else if (body.createTextRange) {
		range = body.createTextRange();
		range.moveToElementText(el);
		range.select();
	}
}

<table id="tableId" border="1">
	<thead>
		<tr><th>Heading 1</th><th>Heading 2</th></tr>
	</thead>
	<tbody>
		<tr><td>cell 1</td><td>cell 2</td></tr>
	</tbody>
</table>

<input type="button" value="select table" onclick="selectElementContents( document.getElementById('tableId') );">

这篇关于使用 Javascript 选择一个完整的表格(要复制到剪贴板)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆