我正在为打印媒体创建一个样式表,其中包含一个内联SVG作为元素的伪类(即 ::before
,::after
的内容)。
在Chrome中进行测试时,它似乎工作得很好,但是当首次在Firefox和Safari中加载页面时,SVG元素不会出现在打印预览中。然后它出现在随后的所有尝试中。
我不确定发生了什么,但是如果我不得不猜测,我的推测是:当页面没有被缓存时,延迟会导致伪元素同时发生在浏览器创建中打印页面。
我很想知道为什么会这样,以及是否有任何解决方案可以可靠地使用SVG伪元素。
这是一个精简的代码示例。请查看您是否可以重现此问题:
var button = document.querySelector('button');
button.addEventListener('click', function () {
window.print();
});

div {
text-align: center;
}
button {
margin: 2em;
padding: 1em 2em;
}
@media print {
button {
display: none;
}
div::before {
content: 'Pseudo-elements';
font-weight: bold;
margin-top: 1em;
}
div::after {
position: relative;
display: block;
margin-top: 1em;
content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><circle cx='50' cy='50' r='50' /></svg>");
}
}
&#13;
<div>
<button>
print
</button>
</div>
&#13;
答案 0 :(得分:1)
我可以责备。
这似乎是加载svg的一个错误,我猜它与任何图像都是一样的。
一种解决方法是使用display: none
var button = document.querySelector('button');
button.addEventListener('click', function() {
window.print();
});
div {
text-align: center;
}
button {
margin: 2em;
padding: 1em 2em;
}
div::after {
display: none;
content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><circle cx='50' cy='50' r='50' /></svg>");
}
@media print {
button {
display: none;
}
div::before {
content: 'Pseudo-elements';
font-weight: bold;
margin-top: 1em;
}
div::after {
opacity: 1;
position: relative;
display: block;
margin-top: 1em;
}
}
<div>
<button>
print
</button>
</div>
另一个是通过js预先加载它。