首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用CSS打印页面的不同部分

使用CSS打印页面的不同部分
EN

Stack Overflow用户
提问于 2014-03-24 13:53:49
回答 1查看 123关注 0票数 0

我有下面的例子(简单的) HTML文件在这里的页面包括4个主要区域headerleft-columnrigh-columnfooter。此外,它还包括两个@media元素screenprint

当我打印页面时,@media screen{...}样式只能调用并打印整个页面。例如,如果我想打印除right-column之外的所有区域,我会在right-column中添加类似.noprint {display:none;}的内容

我想知道的是,我是否可以只使用CSS打印1到2个区域(这5个区域中)?如果这是不可能的,并且需要JS,那么完成这项工作的最小JS代码是什么?

例如,当我打印页面(ctrl+p或command+p)时,我只想打印区域2和区域3。下一次我只想打印2,下次我只想打印4。

EN

回答 1

Stack Overflow用户

发布于 2014-03-24 14:52:18

在执行打印操作之前,您必须使用jQuery为希望可见的项目设置一个类,例如每次使用.visiblePrint并切换。

如果愿意,还可以捕获打印请求:http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

举个例子:

代码语言:javascript
运行
复制
    <script type="text/javascript">
        $( document ).ready(function() {
            printMode = 1;

                var beforePrint = function() {
                        (printMode==3) ? printMode = 1 : printMode++;
                        console.log('Functionality to run before printing.');
                };
                var afterPrint = function() {
                    $('div').removeClass('visiblePrint');
                    switch(printMode) {
                        case 1:
                            $('#print1').addClass('visiblePrint');
                            break;
                        case 2:
                            $('#print2').addClass('visiblePrint');
                            break;
                        case 3:
                            $('#print3').addClass('visiblePrint');
                            break;
                    }

                    console.log('Functionality to run after printing');
                };

                if (window.matchMedia) {
                        var mediaQueryList = window.matchMedia('print');
                        mediaQueryList.addListener(function(mql) {
                                if (mql.matches) {
                                        beforePrint();
                                } else {
                                        afterPrint();
                                }
                        });
                }

                $(window).on('beforeprint', beforePrint);
                $(window).on('afterprint', afterPrint);
                /*window.onbeforeprint = beforePrint;
                window.onafterprint = afterPrint;*/


        }());
    </script>
    <style type="text/css" media="print">
        div {
            display:none;
        }
        .visiblePrint {
            display: block;
        }
    </style>
</head>
<body>
    <div id="print1">Messaggio di stampa 1</div>
    <div id="print2">Secondo messaggio di stampa</div>
    <div id="print3">Viva la mamma</div>
</body>

不幸的是,它是而不是跨浏览器,在chrome中引发2个事件,在火狐中不引发事件…

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22602029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档