开发者

Print Div With Javascript and Preserve Style

开发者 https://www.devze.com 2023-02-03 09:06 出处:网络
I\'m trying t开发者_运维知识库o print a certain div in my application using this javascript with JQuery:

I'm trying t开发者_运维知识库o print a certain div in my application using this javascript with JQuery:

function PrintContent()
{
w=window.open();
w.document.write($('#diary').html());
w.print();
w.close();
}

It opens the div in a new tab and the print options panel opens up but the CSS styles are lost. I have a print.css, set to media="print" however, I think that it's obviously not loading this file in the new tab i.e. it's just loading the div and not the header where the CSS is.

Any idea how I can fix this? My javascript isn't that strong.

Thanks!


Try using this line instead:

w.document.write('<div id="diary">' + $('#diary').html() + '</div>');

You are writing out the inner html of your div and not the actual div tag.

The method above also writes out the div tag with the right id. I only stuck the id in there because you might be formatting div#diary rather than div.

EDIT

This method should keep the styling.

function PrintContent()
{
    var e = document.createElement('div');
    e.id = 'diary';
    e.innerHTML = $('#diary').html();
    document.getElementById('t').appendChild(e);
}

You just have to make a place that this content can be inserted, such as a div with the id of t. Just like the example I posted in the comments.


Because document.write is bad practice:

https://github.com/jasonday/printThis

0

精彩评论

暂无评论...
验证码 换一张
取 消