How to trigger javascript on print event?

后端 未结 4 663
心在旅途
心在旅途 2020-12-16 10:03

Is it possible to trigger a javascript event when a user prints a page? I would like to remove a dependancy on a javascript library, when a user opts to print a page, as the

4条回答
  •  无人及你
    2020-12-16 10:51

    For anyone coming here looking for an option using Bootstrap as I was, I used the following code to achieve this when a print button is clicked. This won't work when they press CTRL + P.

    $("#print_page").click(function(){
    $("#print_section").addClass('visible-print-block');
    window.print();
    $("#print_section").removeClass('visible-print-block');})
    

    You need to add hidden-print to anything you don't want printed and then add an ID (or a class if you have more than one section) of print_section to the bit you want printed! Bit hacky but it works!

提交回复
热议问题