【问题标题】:javascript document.write css doesn't applyjavascript document.write css 不适用
【发布时间】:2016-02-28 20:37:25
【问题描述】:

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 中对此进行测试。

【问题讨论】:

  • 当窗口出现时,我需要我的 div 变为红色”你的意思是当文档加载时?
  • .html() 不包括元素本身。
  • 如果你使用 jQuery,你可以使用$("#dvContainer").css("color", "red");...就这么简单...
  • 我的意思是窗口打印-(在我的页面中红色是从 css 中获取值)。它没有改变颜色。是的,我正在使用 jquery,即使您发送给我的这段代码也没有改变。

标签: javascript jquery css colors


【解决方案1】:

在我们交谈之后,您想要做的是正确设置打印样式。将此添加到 products.css

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

【讨论】:

  • 我仍然认为在里面输入这个是一样的。还是黑的。
  • 您是否在 chrome 打印设置中启用了样式?
  • 不,我没有啊,也许你的权利让我们看看......这些设置在哪里?
  • Chrome -> 打印 -> 更多选项 -> 背景图形
  • 不,不是那样的。它已启用。
【解决方案2】:

终于找到解决办法了!!! 打印媒体类型的引导代码阻止了我,也是阻止我页面中所有其他 css 的错误。 所以我编译了一个没有打印媒体类型的新引导程序,现在可以工作了!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多