【发布时间】: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