我试图在打印时将 css 文件添加到 HTML 内容中。但是没有添加 css 文件。我得到没有 CSS 的输出。谁能帮帮我...
这是我的代码
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script>
<script type="text/javascript">
function PrintElem(elem)
{
Popup($(elem).html());
}
function Popup(data)
{
var mywindow = window.open('', 'mydiv', 'height=700,width=1200');
mywindow.document.write('<html><head><title></title>');
mywindow.document.write('<link rel="stylesheet" href="print.css" type="text/css" media="print"/>');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
return true;
}
</script>
</head>
<body>
<div id="mydiv">
This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante.
</div>
<div>
This will not be printed.
</div>
<div id="anotherdiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />
</body>
</html>
这是我的 CSS 文件“print.css”
@media print {
#mydiv {
border: 10px solid !important;
color: red;
font-size:20px !important;
}
}
最佳答案
找出问题所在:
- 您正在将元素“mydiv”传递给函数 PrintElem。
- PrintElem 函数只获取内部 html 而不是完整的 div
- 你正在将它发送到另一个函数 Popup(仅 mydiv 的 innerhtml)
- Popup 正在打开带有一些 html、css 和 js 的新页面
- 在数据变量中你只能得到文本而不是 DIV 'mydiv',这实际上是需要的,而不仅仅是内部 html。
- 因此,当您的页面加载时,它找不到您正在应用 css 的 mydiv。
解决方案请将整个 div 而不是 div.html() 传递给 Popup 函数
尝试这样的事情或尝试其他方式这样做
function PrintElem(elem)
{
Popup($(elem)); // send div not html only
}
关于javascript - 打印时无法将 css 文件添加到 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32225406/