如何使用PhantomJS检测网页的背景颜色
How can I detect the background color of a webpage with PhantomJS?
我使用PhantomJS通过render()函数对一些网页进行光栅化,有时生成的图像会有黑色背景(正如常见问题解答底部所说,这应该是一种正常行为)。
但如果网页没有设置背景颜色,我想只设置白色背景,如下所示:
page.evaluate(function() {
if (getComputedStyle(document.body, null).backgroundColor === 'transparent') {
document.body.bgColor = 'white';
}
});
但它根本不起作用。我也尝试过:
=== 'rgba(0, 0, 0, 0)'
但无济于事。
我在这里错过了什么?
html
标记上设置背景色。示例如下:http://helpdesk.symphonical.com/hc/en-us
设置"body"背景颜色将覆盖"html"标记中的颜色。
我最终为根html
标签设置了颜色,这样即使body
有其他颜色,它也会在page.evaluate
:中从html
隐藏我们的自定义颜色
// 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);
}
您可以添加一个对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; }
。
我想我发现了问题。实际上:
document.body.bgColor = 'white'
不起作用。我用的是:
document.body.style.backgroundColor = '#ffffff'
现在我得到了白色背景。
相关文章:
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何使用jquery更改html中的背景颜色
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- JS幻灯片与CSS背景颜色变化
- DT数据表背景颜色为黑色,但仍有悬停和选择颜色
- Javascript通过列表项的函数和css来更改背景颜色
- Javascript没有从数组中选择背景颜色
- 使用圆中的数组更改背景颜色项目
- 如何用jquery动画改变背景颜色,就像一个过渡
- 使用jquery交换并保存背景颜色
- j查询如何设置/取消设置下拉菜单的背景颜色
- 使用angularjs根据时间更改背景颜色
- 设置Dojo量表的背景颜色
- javascript样式的背景颜色在设置时闪烁.ASP.NET
- 使用javascript更改任意文本的背景颜色
- 在用Javascript更改背景颜色后:hover don'不要改变颜色
- 图像内部的透明背景颜色不受影响
- jQuery mobile-动态更改ui页面背景颜色
- 切换按钮的背景颜色
- JavaScript更改类的背景颜色