2013-02-11 139 views
3

尝试打开一个新窗口以包含仅用于打印的元素。但它在IE8中不起作用。打开新窗口打印元素

function printElement(elementId) { 
    var printWindow = window.open('', '_blank', 
    'status=0,toolbar=0,location=0,menubar=1,resizable=1,scrollbars=1'); 

    printWindow.document.write("<html><head></head><body></body></html>"); 

    var head = jQuery('head').clone(); 
    var printElement = jQuery('#' + elementId).clone(); 

    jQuery(printWindow.document).find('head').replaceWith(head); // does not work in IE8 
    var body = jQuery(printWindow.document).find('body'); 
    body.empty(); 
    body.append(printElement); // does not work in IE8 
    return false; 
} 

感谢您的帮助。

回答

3

这个怎么样?如果我明白你想要正确做什么,这应该适合你。在IE 8中测试。

Working example on JSBin

HTML:

<a href="#" id="one" class="trigger">Print One</a> 
<a href="#" id="two" class="trigger">Print Two</a> 

的JavaScript:

var $trigger = $(".trigger"), 
    printElement = function(id) { 
     var printWindow = window.open('','_blank','status=0,toolbar=0,location=0,menubar=1,resizable=1,scrollbars=1'), 
      html = $('html').clone(), 
      printElement = $('#' + id).clone(), 
      body; 

     printWindow.document.write("<!DOCTYPE html><head></head><body></body></html>"); 

     $(printWindow.document).find('html') 
          .replaceWith(html); 

     body = $(printWindow.document).find('body') 
            .html(printElement); 
    }; 

$trigger.on("click", function(e) { 
    var id = $(this).attr("id"); 

    e.preventDefault(); 

    printElement(id); 
});