【问题标题】:window.matchMedia('print') failing in Firefox and IEwindow.matchMedia('print') 在 Firefox 和 IE 中失败
【发布时间】:2016-01-15 21:04:12
【问题描述】:

我有一个打印按钮,可以在任何网页上启动打印功能。一旦用户单击该按钮,该按钮就会隐藏,并显示用户是否已完成打印或在打印窗口中按下关闭。它在 Chrome 中运行良好,但在 Firefox 和 IE 中失败。

<input type="button" onclick="launchPrint()" value= "Print me" />


function launchPrint(){
$(".print-box").hide();
window.print();
}

(function() {
    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (!mql.matches) {
                $(".print-box").show();
            }
        });
    }
}());

有什么我可能遗漏的建议吗?

【问题讨论】:

    标签: javascript html printing matchmedia


    【解决方案1】:

    不幸的是,我和你遇到了同样的问题,我做了一些研究。目前看来,最新版本的FF和IE仍然存在该错误,尚未修复。

    您可以查看 Firefox 的这个错误:https://bugzilla.mozilla.org/show_bug.cgi?id=774398

    我发现另一个人和我们有同样的问题,但没有一个真正令人满意的答案: https://social.technet.microsoft.com/Forums/office/en-US/bc3ca05e-b4ef-425b-8bbd-d3f700a8c85e/windowmatchmedia-not-firing-for-print-in-ie?forum=ieitprocurrentver

    如果我遇到任何解决方案,我会编辑它。

    我主要使用与您相同的代码作为 highchart 在打印前调整大小的示例:

    function printUpdate() {
        jQuery.each(Highcharts.charts, function(index, value){
            value.reflow();
        });
    };
    var mediaQueryList = window.matchMedia('print');
    if(navigator.appVersion.indexOf("MSIE 8.")!==-1)//For IE8
    {
        document.attachEvent(function (mql){printUpdate();}, mediaQueryList);
    }
    else
    {
        if (window.matchMedia) {
            mediaQueryList.addListener(function (mql) {
                if (mql.matches)
                {
                    printUpdate();
                }
            });
        }
    }
    
    window.onbeforeprint = printUpdate;
    

    这在 chrome 中可以正常工作。但 FF 和 IE11 不会触发该事件。

    【讨论】:

    • @clever_bassi 这应该是公认的答案:这个错误在 2021 年仍然存在......我还没有找到任何缓解措施,如果你监听这个事件来触发 JS 元素调整大小。
    【解决方案2】:

    您可能想查看onafterprint 事件。至少这是由 Firefox 和 IE 触发的,因此对于您的用例,使用潜在的保护(以确保事件不会多次触发)您可以同时收听 matchMedia("print")onafterprint 事件。

    【讨论】:

    • 请注意它们不等效: - 在将媒体查询应用于您的页面之前调用 beforeprint(基本上您的页面尚未“调整大小”以进行打印) - 在您打印之后调用 afterprint/取消打印 - 媒体查询更改发生在 => 这就是您想要触发“调整大小”事件并强制 JS 在打印之前重排,其他事件将不起作用
    猜你喜欢
    • 2017-09-27
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多