开发者

Select and copy table to clipboard

I want to select table without headers, and it works, but 开发者_如何学CI cannot get it so, that it would copy to clipboard.

Here's the page: http://tuudik.lohv.eu/Asjad/EURXML/

Here's the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>ECB kursid seisuga: 2011-04-01 </title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
<style type="text/css">
table
{
border-collapse:collapse;
}
table, td, th
{
border:1px solid black;
}
</style>
<script type="text/javascript">
    function selectElementContents(el) {
        var body = document.body, range, sel;
        if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
            range.execCommand('Copy');
        } else if (document.createRange && window.getSelection) {
            range = document.createRange();
            range.selectNodeContents(el);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
            sel.execCommand('Copy');
        }

    }
</script>
</head>

<body>
<table cellpadding="2">
<thead>

    <tr>
        <th>Valuuta</th>
        <th>Kurss</th>
    </tr>
</thead>
<tbody id="currencies">
<tr><td>USD</td><td>1,4141</td></tr><tr><td>JPY</td><td>118,56</td></tr><tr><td>DKK</td><td>7,4564</td></tr><tr><td>GBP</td><td>0,88150</td></tr><tr><td>NOK</td><td>7,8055</td></tr><tr><td>RUB</td><td>40,1500</td></tr><tr><td>CAD</td><td>1,3686</td></tr></tbody>

</table>
<input type="button" value="select table"
   onclick="selectElementContents( document.getElementById('currencies') );">
</body>
</html>


This works for me on IE8:

    var table = document.getElementById('copyHtmlToClipboard');
    // Below line is essential !!!
    table.contentEditable = 'true';   

    var controlRange = document.body.createControlRange();
    controlRange.addElement(table);
    controlRange.execCommand("Copy");


In most browsers it isn't possible to copy to the system clipboard. To do this you need to use a hack. The most common way is to use Flash. ZeroClipboard does this and appears to work quite well.

By the way, execCommand() is a method of document and TextRange objects, not Selection objects, so sel.execCommand("Copy") couldn't possibly work.

UPDATE

I've never actually used ZeroClipboard. Having looked at the docs, it doesn't look like it does what I had hoped (there seems to be no way to copy rich text) and is even more of a gruesome hack than I thought. You could copy the table's content as text via innerHTML using ZeroClipboard, but whether this is acceptable or not depends on what you're hoping the user can do with the copied content.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜