Print
only?

前端 未结 30 2204
暖寄归人
暖寄归人 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:48

    Here is a general solution, using CSS only, which I have verified to work.

    @media print {
      body * {
        visibility: hidden;
      }
      #section-to-print, #section-to-print * {
        visibility: visible;
      }
      #section-to-print {
        position: absolute;
        left: 0;
        top: 0;
      }
    }
    

    Alternative approaches aren't so good. Using display is tricky because if any element has display:none then none of its descendants will display either. To use it, you have to change the structure of your page.

    Using visibility works better since you can turn on visibility for descendants. The invisible elements still affect the layout though, so I move section-to-print to the top left so it prints properly.

提交回复
热议问题