【问题标题】:printing only a part of the page (container element and its content) [duplicate]仅打印页面的一部分(容器元素及其内容)[重复]
【发布时间】:2015-10-16 18:31:01
【问题描述】:

我试图只打印我页面的一部分,例如从指定的元素容器包装器中,以下是我尝试过的,但不幸的是似乎不起作用。

$("#j_print_container").print(); //window.print()

它给了我一个错误:

打印不是函数

有什么想法、帮助、线索、建议吗?

【问题讨论】:

标签: javascript jquery printing


【解决方案1】:

试试这个

如果你需要 css/js 然后像下面这样添加或删除

function printDiv(){    
    var divContent=$('#j_print_container').html();  
    var mywindow = window.open('', 'my div', 'height=600,width=750');
    var htm = '<html><head><title>Receipt</title><script src="'+contextPath+'scripts/lib/jquery.min.js" ></script><link rel="stylesheet" href="'+contextPath+'styles/style.css" type="text/css" /><link rel="stylesheet"'+
              'href="'+contextPath+'styles/custom.css" type="text/css" /><link rel="stylesheet" href="'+contextPath+'styles/font-awesome.min.css" type="text/css" />'+
              '<link rel="stylesheet" href="'+contextPath+'styles/bootstrap.min.css" type="text/css" />'+'</head><body >'+divContent;
    htm=htm+'</body></html>';
    mywindow.document.write(htm);
    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10
    mywindow.print();
    mywindow.close();       
}

【讨论】:

  • 这不起作用,请您提供一个sn-p或小提琴吗?
  • @Code Demon 我在很多地方都使用了这个功能,它工作正常我会在一段时间后添加小提琴
  • 什么是 contextPath?
  • jsfiddle 不允许 write 方法,所以对于演示需要您的邮件 id 来发送演示
  • 啊,好吧,你的意思是我的项目链接,比如'project.net'?
【解决方案2】:

print 不是 jQuery 元素上的函数。

正如 cmets 中所指出的,here 已经有几个很好的答案,还有一个 CSS 解决方案 here(不是公认的答案——那是垃圾!)。

这里有几个我敲过的方法。它并不像看起来那么简单 - 您可能仍然需要 CSS,而第二个可能不适用于更复杂的页面,但它可以让您了解您想要实现的目标。

$.fn.print = function(){
    var content = $(this).html();
    var w = window.open('about:blank','', 'width=800,height=600,top=100,left=100');
    w.document.write(content);
    w.print();
    w.close();
};

$.fn.print2 = function(){
    $('*').not(this).addClass('hidden-for-print').hide();
    $(this).children().removeClass('hidden-for-print').show();
    $(this).parents().removeClass('hidden-for-print').show();
    window.print();
    $('.hidden-for-print').show();
};

http://jsfiddle.net/daveSalomon/et7xxd2s/1/

【讨论】:

  • 不错!第一个 jquery 函数有效,但是如果我要使用自定义样式表附加打印,有什么办法可以做到吗?
  • 当然,您可以在第一个样式表中包含样式表。 w.document.write(content); w.document.write('&lt;link type="text/css" rel="stylesheet" href="/styles/foo.css"/&gt;');.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2018-06-17
  • 2017-12-05
相关资源
最近更新 更多