我有一个带有一些文本区域的表单,当文本超出文本框时允许滚动条。用户希望能够打印屏幕,但此文本不可见。如何使所有文本都可见以供打印?我是否最好制作一个打印到 pdf 的链接或其他东西?
最佳答案
你不能单独使用 CSS 解决这个问题。
为什么纯 CSS 解决方案不够用(带演示)
让我说服您涉及打印样式表和溢出:可见
的答案是不够的。打开this page并查看来源。正是他们建议的,对吧?现在打印预览它(比如,在 OS X 上的 Chrome 13 中,就像我一样)。请注意,当您尝试打印时,您只能看到一两行便条!
这里又是我的测试用例的 URL:https://alanhogan.github.io/web-experiments/print_textarea.html
解决方案:
一个 JavaScript 链接,它打开一个新窗口并将文本区域的内容写入其中以供打印。或者:
当 textarea 更新时,将其内容复制到另一个在屏幕上隐藏但在打印时显示的元素。
(如果您的
textarea
是只读的,那么服务器端解决方案也是可行的。)
请注意,textarea
默认情况下处理空格的方式与 HTML 不同,因此您应该考虑在新窗口中应用 CSS white-space: pre-wrap;
分别打开或打开你的助手div
。然而,IE7 和更早的版本不理解 pre-wrap
,所以如果这是一个问题,要么接受它,要么使用解决方法。或者使弹出窗口实际上是纯文本,字面意思是使用媒体类型 text/plain
(这可能需要服务器端组件)。
“打印助手”解决方案(附代码+demo)
我创建了一个 demo of one JavaScript technique .
核心概念是将文本区域内容复制到另一个打印助手。代码如下。
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。 .
关于html - textarea溢出时打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4435906/