如何使用 Javascript 为 asp:label 执行“全选”和“复制到剪贴板”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5117442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I do a "select all" and "copy to clipboard" with Javascript for an asp:label?
提问by Ben
I want to copy the content of an asp:label using javascript.
我想使用 javascript 复制 asp:label 的内容。
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.
该标签包含一些格式化的 html。我想保留格式,获得与用鼠标在屏幕上突出显示它相同的效果,然后复制到(例如)word 文档中。
采纳答案by NakedBrunch
Updated
更新
The following will highlight the desired div and then copy the HTML to the clipboard. Go to Word and press CTRL+Vto paste the formatted html into a document.
以下将突出显示所需的 div,然后将 HTML 复制到剪贴板。转到 Word 并按CTRL+V将格式化的 html 粘贴到文档中。
<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>

