English 中文(简体)
Select a complete table with Javascript (to be copied to clipboard)
原标题:

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.

Any ideas?

最佳回答

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

(Updated 7 September 2012 after Jukka Korpela s comment pointing out that the previous version didn t work in IE 9 standards mode)

Demo: http://jsfiddle.net/timdown/hGkGp/749/

Code:

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 ) );">
问题回答

Just to make the code proposed by Tim Down more complete, allowing de selected content to be automatically copied to clipboard:

<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 ) );">

I got it to work in IE9 finally by using the following script

NOTE: It doesn t work on html tables. It HAS to be a DIV. So just put a wrapper DIV around the table you need to select!

First I changed the HTML button code a bit:

<input type="button" value="Mark table"    onclick="SelectContent( table1 );">  

Then changed the javascript to:

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);              
 }  
}

Here is what I have used. It also make the copy command so all you have to do is use the paste command in the document you want to place it into. Basically you wrap the content you want to copy in a div, grab it using innerHTML and copy it to the clipboard. I have not tested it on all browsers but it works in 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>




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签