Print
only?

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

    I didn't really like any of these answers as a whole. If you have a class (say printableArea) and have that as an immediate child of body, then you can do something like this in your print CSS:

    body > *:not(.printableArea) {
        display: none;
    }
    
    //Not needed if already showing
    body > .printableArea {
        display: block;
    }
    

    For those looking for printableArea in another place, you would need to make sure the parents of printableArea are shown:

    body > *:not(.parentDiv),
    .parentDiv > *:not(.printableArea) {
        display: none;
    }
    
    //Not needed if already showing
    body > .printableArea {
        display: block;
    }
    

    Using the visibility can cause a lot of spacing issues and blank pages. This is because the visibility maintains the elements space, just makes it hidden, where as display removes it and allows other elements to take up its space.

    The reason why this solution works is that you are not grabbing all elements, just the immediate children of body and hiding them. The other solutions below with display css, hide all the elements, which effects everything inside of printableArea content.

    I wouldn't suggest javascript as you would need to have a print button that the user clicks and the standard browser print buttons wouldn't have the same effect. If you really need to do that, what I would do is store the html of body, remove all unwanted elements, print, then add the html back. As mentioned though, I would avoid this if you can and use a CSS option like above.

    NOTE: You can add whatever CSS into the print CSS using inline styles:

    
    

    Or like I usually use is a link tag:

    
    

提交回复
热议问题