最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Printing contents of a div - Stack Overflow

programmeradmin2浏览0评论

The contents of the following div is derived dynamically: i.e a table is added dynamically to this div with some button.

My question is how to print the content of this div(window.print) and not other things in the page

<div id="newdiv" name="newdiv"></div>

Thanks.

The contents of the following div is derived dynamically: i.e a table is added dynamically to this div with some button.

My question is how to print the content of this div(window.print) and not other things in the page

<div id="newdiv" name="newdiv"></div>

Thanks.

Share Improve this question edited Apr 3, 2010 at 19:50 Veger 37.9k11 gold badges108 silver badges117 bronze badges asked Apr 3, 2010 at 19:40 HulkHulk 34.2k65 gold badges150 silver badges217 bronze badges 3
  • @Hulk as I said in the other question, please leave feedback about unsatisfactory answers here instead of opening a new one. – Pekka Commented Apr 7, 2010 at 13:51
  • Pekka no offence ,i am marking it as answered. – Hulk Commented Apr 8, 2010 at 4:47
  • no offence taken, if the answer didn't help you you are free to un-check it. If a solution didn't work out, just give feedback to that effect and you will usually get new options. – Pekka Commented Apr 8, 2010 at 8:25
Add a ment  | 

3 Answers 3

Reset to default 7

Two ideas:

  • Introduce a print stylesheet

     <link rel="stylesheet" href="print.css" type="text/css" media="print"  />
    

    that will give every element display: none except for newdiv:

     * { display: none } /* This should hide all elements */
     div#newdiv { display: block } /* This should make newdiv visible again */
    

    I can't test this right now but I can't see why this wouldn't work.

  • Copy the contents of the div into a newly created iframe element using JavaScript and print that.

    Lots of obstacles on the road that way, though. I'd try using CSS first.

Clever thinking Pekka, but it doesn't work quite like that, after using a global display:none you would have to redisplay every single element that needs to be displayed, including all parent elements. Best way would be to hide all the elements that should not be printed, good news is that you only need to hide the parent element and everything in it will be hidden.

There is by the way no need for an extra style sheet, a block in an existing sheet can be used (it must be placed at the end of the last sheet):

@media print{
    .noprint{
        display:none;
    }
}

Now a block can be hidden from printing simply by giving its container the noprint class.

Your best bet is to create a media-specific style sheet.

http://www.alistapart./articles/goingtoprint/

发布评论

评论列表(0)

  1. 暂无评论