javascript - 打印时无法将 css 文件添加到 html

标签 javascript jquery html css

我试图在打印时将 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;
	}
}

最佳答案

找出问题所在:

  1. 您正在将元素“mydiv”传递给函数 PrintElem。
  2. PrintElem 函数只获取内部 html 而不是完整的 div
  3. 你正在将它发送到另一个函数 Popup(仅 mydiv 的 innerhtml)
  4. Popup 正在打开带有一些 html、css 和 js 的新页面
  5. 在数据变量中你只能得到文本而不是 DIV 'mydiv',这实际上是需要的,而不仅仅是内部 html。
  6. 因此,当您的页面加载时,它找不到您正在应用 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/

相关文章:

javascript - 如何根据其值更改下拉列表值样式?

javascript - Ionic 2(点击)触发两次 iOS 10.3.1

javascript - 无法将动态 id 添加到 jquery 元素

javascript - 如何检查给定的 Web 应用程序中是否使用了 jQuery?

javascript - 通过 Panzoom 变换放大时获取 Canvas 点击坐标

css - div 内的渐进增强

html - 使用 CSS 在 div 中保留 float 图像

java - 临时编码的工作流程

jquery - Grails remotefunction用Jquery填充dropdownlist

jQuery - 单击链接后将 html 文件加载到 div 中