javascript document.write css不适用

时间:2016-02-28 20:37:26

标签: javascript jquery css colors

HTML:

<div id="dvContainer">
        This content needs to be printed.
</div>
<button>Print</button>

JavaScript的:

 $("button").on("click", function(){
    var divContents = $("#dvContainer").html();
            var printWindow = window.open('', '', 'height=400,width=800');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/product.css\" />");
            //printWindow.document.write("<style>#dvContainer{color: red;}</style>");

            printWindow.document.write('</head><body>');
            printWindow.document.write(divContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
});

当窗口出现时,我需要将div更改为红色,但没有任何反应。

我尝试使用样式代码,但我的元素仍然是黑色的。我也尝试过媒体印刷,但没有。

有什么建议吗?我做错了什么?
我在最新版本的Chrome和jQuery 1.9.1中对此进行了测试。

2 个答案:

答案 0 :(得分:1)

在我们的对话之后,您要做的是正确设置打印样式。将其添加到products.css

@media print {
   body {
      background-color: red;
   }
 }

答案 1 :(得分:0)

最后我找到了解决方案! 打印媒体类型的bootstrap代码阻止了我,也是阻止我页面中所有其他css的错误。 所以我在没有打印介质类型的情况下编写了一个新的bootstrap,现在正在工作!!!