首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用css样式打印div

问使用css样式打印div
EN

Stack Overflow用户
提问于 2020-08-27 18:04:25
回答 2查看 447关注 0票数 4

我编写了一个只打印div的脚本,但是当我看到预览时,它没有使用添加的CSS对页面进行“格式化”。

HTML部件:

代码语言:javascript
复制
<center>Do not print this</center>              
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
            <input type='button' value='Print' onClick='Print()' />

JS部件

代码语言:javascript
复制
function Print(){
     var corpo = document.getElementById('content').innerHTML;

     var a = window.open('','','width=640,height=480');
     a.document.open("text/html");
     a.document.write("<html><head><link rel=\"stylesheet\" href=\"./style.css\"></head><body><div class=\"print\">");
     a.document.write(corpo);
     a.document.write("</div></body></html>");
     a.document.close();
     a.print(); 
}

一个实时版本:https://codepen.io/Pop1111/pen/Vwabbzd

看起来它只是在之后才加载css。

有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-27 18:13:14

您的代码将创建无效的HTML

试一试

​

代码语言:javascript
复制
function Print() {
  var corpo = document.getElementById('content').innerHTML;
  const html = [];
  html.push('<html><head>');
  // assuming the first stylesheet on the parent page - use a different selector if not
  // or use +location.protocol+'//'+location.host+'/style.css">'
  html.push('<link rel="stylesheet" href="' + document.querySelector("link[rel=stylesheet]").href + '">');
  html.push('</head><body onload="window.focus(); window.print()"><div>');
  html.push(corpo);
  html.push('</div></body></html>');
  console.log(html)
  /*  this will not work in the snippet - uncomment on your server
  var a = window.open('', '', 'width=640,height=480');
  a.document.open("text/html");
  a.document.write(html.join(""));
  a.document.close();
  */
}
代码语言:javascript
复制
<html>

<head>
  <link rel="stylesheet"  href="test.css" />
</head>

<body>
  <center>Do not print this</center>
  <div>Hi mom!</div>
  <center>Print this</center>
  <div id="content" class="print">Hi dad!</div>
  <input type='button' value='Print' onClick='Print()' />
</body>

</html>

​

票数 1
EN

Stack Overflow用户

发布于 2020-08-27 18:10:23

您的新文档未保存,因此没有预期的路径,因此CSS文件的相对引用找不到CSS。

要使其按预期工作,您需要将CSS引用更改为绝对引用,或者首先添加代码以保存新的HTML文件。

这只是你测试它的方式,还是你的生产版本也会这样工作?(新建文件,未保存,然后打印)。

您可以始终将实际的CSS本身插入到样式标签之间的新文档的头部,而不仅仅是对CSS文件的引用。试试看。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63613666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档