你不能单独使用 CSS 解决这个问题。
为什么纯 CSS 解决方案不足(附演示)
让我说服您涉及打印样式表和overflow: visible 的答案是不够的。打开this page 并查看源代码。正是他们的建议,对吧?现在打印预览它(例如,在 OS X 上的 Chrome 13 中,就像我一样)。请注意,当您尝试打印时,您只能看到一两行注释!
这是我的测试用例的 URL:https://alanhogan.github.io/web-experiments/print_textarea.html
解决方案:
一个 JavaScript 链接,它打开一个新窗口并将 textarea 的内容写入其中以进行打印。或者:
更新文本区域时,将其内容复制到另一个元素,该元素在屏幕上隐藏但在打印时显示。
(如果您的textarea 是只读的,那么服务器端解决方案也是可行的。)
请注意textareas 对待空白的方式与默认情况下 HTML 不同,因此您应该考虑分别在打开的新窗口中应用 CSS white-space: pre-wrap; 或将 CSS div 应用到帮助程序 div。但是,IE7 和更早版本不理解 pre-wrap,所以如果这是一个问题,要么接受它,要么为他们使用解决方法。或者使弹出窗口实际上是纯文本,使用媒体类型text/plain(可能需要服务器端组件)提供。
“打印助手”解决方案(带代码+演示)
我创建了一个demo of one JavaScript technique。
核心概念是将 textarea 内容复制到另一个打印助手。代码如下。
HTML:
<textarea name="textarea" wrap="wrap" id="the_textarea">
</textarea>
<div id="print_helper"></div>
CSS(全部/非打印):
/* Styles for all media */
#print_helper {
display: none;
}
CSS(打印):
/* Styles for print (include this after the above) */
#print_helper {
display: block;
overflow: visible;
font-family: Menlo, "Deja Vu Sans Mono", "Bitstream Vera Sans Mono", Monaco, monospace;
white-space: pre;
white-space: pre-wrap;
}
#the_textarea {
display: none;
}
Javascript(使用 jQuery):
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
function copy_to_print_helper(){
$('#print_helper').text($('#the_textarea').val());
}
$('#the_textarea').bind('keydown keyup keypress cut copy past blur change', function(){
copy_to_print_helper(); // consider debouncing this to avoid slowdowns!
});
copy_to_print_helper(); // on initial page load
});
</script>
同样,成功基于 JavaScript 的演示位于 https://alanhogan.github.io/web-experiments/print_textarea_js.html。