我从这个网站得到这段代码来打印一个 div:
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
$('button').on('click',function(){
printData();
})
如何将 css 代码添加到此 javascript 以应用于 id='table' 的表?
table, td, th {
border: 1px solid black;
text-align:justify;
}
th {
background-color: #7a7878;
text-align:center
}
最佳答案
请看:http://jsfiddle.net/rhjv1u11/
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
var css =`table, td, th {
border: 1px solid black;
text-align:justify;
}
th {
background-color: #7a7878;
text-align:center
}`;
var div = $("<div />", {
html: '­<style>' + css + '</style>'
}).appendTo( newWin.document.body);
newWin.print();
newWin.close();
}
$('button').on('click',function(){
printData();
});
该示例仅插入包含您的规则的样式元素。 如果您需要分配的 CSS 与示例所建议的一样少(并且不需要大量维护),那么这是一个足够的解决方案。
如果它更复杂,您应该访问 newWin.document.head
并插入一个节点来加载外部 CSS。这看起来像这样:
var linkElement=document.createElement("link");
linkElement.setAttribute("rel", "stylesheet");
linkElement.setAttribute("type", "text/css");
linkElement.setAttribute("href", "your.css.file.here.css")
newWin.document.getElementsByTagName("head")[0].appendChild(linkElement)
关于javascript打印特定的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462909/