开发者

How do I do a "select all" and "copy to clipboard" with Javascript for an asp:label?

I want to copy the content of an asp:label using javascript.

I can do it using this method:

strContent = document.getElementById('MainContent_lblHtm开发者_开发百科l').innerText;
window.clipboardData.setData("Text", strContent);

but it strips the formatting and just copies text. (I assume because the dataformat is set to "text".)

The label contains some formatted html. I want to preserve the format, getting the same effect as if I were to highlight it on screen with my mouse, and then copy into (for example) a word document.


Updated

The following will highlight the desired div and then copy the HTML to the clipboard. Go to Word and press CTRL+V to paste the formatted html into a document.

<script type="text/javascript">
    function CopyHTMLToClipboard() {    
        if (document.body.createControlRange) {
            var htmlContent = document.getElementById('MainContent_lblHtml');
            var controlRange;

            var range = document.body.createTextRange();
            range.moveToElementText(htmlContent);

            //Uncomment the next line if you don't want the text in the div to be selected
            range.select();

            controlRange = document.body.createControlRange();
            controlRange.addElement(htmlContent);

            //This line will copy the formatted text to the clipboard
            controlRange.execCommand('Copy');         

            alert('Your HTML has been copied\n\r\n\rGo to Word and press Ctrl+V');
        }
    }    
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜