Print
only?

前端 未结 30 1595
暖寄归人
暖寄归人 2020-11-22 00:25

How do I print the indicated div (without manually disabling all other content on the page)?

I want to avoid a new preview dialog, so creating a new window with this

30条回答
  •  囚心锁ツ
    2020-11-22 00:52

    I have a better solution with minimal code.

    Place your printable part inside a div with an id like this:

    Print me

    Then add an event like an onclick (as shown above), and pass the id of the div like I did above.

    Now let's create a really simple javascript:

    function printDiv(divName) {
         var printContents = document.getElementById(divName).innerHTML;
         var originalContents = document.body.innerHTML;
    
         document.body.innerHTML = printContents;
    
         window.print();
    
         document.body.innerHTML = originalContents;
    }
    

    Notice how simple this is? No popups, no new windows, no crazy styling, no JS libraries like jquery. The problem with really complicated solutions (the answer isn't complicated and not what I'm referring to) is the fact that it will NEVER translate across all browsers, ever! If you want to make the styles different, do as shown in the checked answer by adding the media attribute to a stylesheet link (media="print").

    No fluff, lightweight, it just works.

提交回复
热议问题