在页面上打印元素内容的跨浏览器解决方案是什么?

What is a cross browser solution for printing the contents of an element on a page?

本文关键字:浏览器 解决方案 是什么 打印 元素      更新时间:2023-09-26

我目前正在尝试打印页面上元素的内容,并且我找到了以下资源,

http://www.808.dk/?code-javascript-print
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/108117
http://vikku.info/codesnippets/javascript/print-div-content-print-only-the-content-of-an-html-element-and-not-the-whole-document/

他们都在做一些我已经有的变化,就像下面这样,

function printelement() {
    var parentdiv = $(this).parent().parent();
    var iframeEle = $(document.createElement("iframe")).attr("id", "print" + formParams.fpid).css({ width: "2250px", display: "none" }).appendTo("body");
    var doc = document.getElementById("print" + formParams.fpid).contentWindow.document;
    doc.open();
    //get stylesheets
    $("link[type='text/css']").each( function() {
        doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
    });
    //writes all the contents of div to new iframe
    $(parentdiv).each( function() {
        doc.write($(this).html());
    });
    //print the iframe
    var giframe = parentdiv.contents().find("iframe");
    var printdiv2 = giframe.prevObject[0].id;
    if(printdiv2) {
        if($.browser.msie) {
            var iedoc = giframe.prevObject[0].contentWindow.document;
            iedoc.execCommand('print', false, null);
        } 
        else { giframe.prevObject[0].contentWindow.print(); }
    } 
    else {
         if($.browser.msie){
            doc.execCommand('print', false, null);
         } 
         else { iframeEle[0].contentWindow.print(); }
    }
}

这似乎在FF和Chrome中工作得很好(尽管Chrome一直告诉我我不能在一定时间内打印)。然而,在IE中它只是给我空白的结果。我怎样才能让这段代码跨浏览器,或者做不同的?

与其乱用iframe(对我来说有点粗糙),不如这样做:

  • <body>中的所有内容包装到<div id="mainContent">...</div>
  • 当用户选择打印时,将该特殊元素放在单独的div中,隐藏#mainContent,并打印整个页面
  • (确保你有所有的CSS设置隐藏背景等打印时)
  • 包含返回"正常"视图的链接,该链接将恢复页面
  • (你可能也想通过打印特定的CSS隐藏"关闭打印视图"链接)

if ($('#mainContent').length == 0)
   $('body').children().wrapAll('<div id="mainContent" />');
var toPrint = $('#whateverToPrint');
var origParents = [toPrint.prev(), toPrint.parent()];
toPrint.appendTo('body').wrap('<div id="printWrapper"></div>');
$('<a href="#">Close Print View</a>').appendTo('#printWrapper').click(function(e)
{
    e.preventDefault();
    // Move the element back into place
    if (origParents[0].length > 0)
        toPrint.insertAfter(origParents[0])
    else
        toPrint.prependTo(origParents[1]);
    // Remove wrapper and restore original content
    $('#printWrapper').remove();
    $('#mainContent').show();
});
$('#mainContent').hide();
setTimeout(function()
{
    window.print();
}, 100); // wait for DOM to catch up

听起来不错,还是我在重新发明轮子?