admin管理员组

文章数量:1414605

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

I can do it using this method:

strContent = document.getElementById('MainContent_lblHtml').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.

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

I can do it using this method:

strContent = document.getElementById('MainContent_lblHtml').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.

Share Improve this question asked Feb 25, 2011 at 12:51 BenBen 4,3199 gold badges69 silver badges105 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

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

            //Unment 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>

本文标签: