我正在使用PhantomJS使用render()函数栅格化一些网页,有时候生成的图像有黑色背景(这应该是正常行为,如{{3}的底部所说})。
但是如果网页没有设置背景颜色,我想设置白色背景 ,如下所示:
page.evaluate(function() {
if (getComputedStyle(document.body, null).backgroundColor === 'transparent') {
document.body.bgColor = 'white';
}
});
但它根本不起作用。我也尝试过:
=== 'rgba(0, 0, 0, 0)'
无济于事。
我在这里缺少什么?
答案 0 :(得分:2)
请注意,某些页面可以在根html
标记上设置背景颜色。示例在这里:
http://helpdesk.symphonical.com/hc/en-us
设置'body'背景颜色将覆盖'html'标签的颜色。
我最终设置了根html
标记的颜色,这样即使body
有其他颜色,它也会隐藏html
中page.evaluate
的自定义颜色:
// test the top-level HTML tag since it can also contain backgroundColor
// and we don't wont to override it in body
if (getComputedStyle(document.documentElement, null).backgroundColor === 'rgba(0, 0, 0, 0)') {
console.log('document.documentElement backgroundColor is transparent, setting color to white');
var style = document.createElement('style'),
text = document.createTextNode('body { background: #fff }');
style.setAttribute('type', 'text/css');
style.appendChild(text);
document.documentElement.insertBefore(style, document.documentElement.firstChild);
}
答案 1 :(得分:1)
您可以将body的最低有用特性(1)附加到头部的第一个元素。引擎会自动使用后来出现的背景。如果之后没有,将使用这个。
page.evaluate(function(){
var s = document.createElement('style');
s.setAttribute("type", "text/css");
s.innerText = "body { background-color: white; }";
// assuming head exists and is not empty:
document.head.insertBefore(s, document.head.firstChild);
});
您也可以尝试使用特异性为0的* { background-color: white; }
。
答案 2 :(得分:0)
我想我发现了这个问题。实际上:
document.body.bgColor = 'white'
不起作用。我改为使用了:
document.body.style.backgroundColor = '#ffffff'
现在我得到了白色背景。