【问题标题】:How can I detect the background color of a webpage with PhantomJS?如何使用 PhantomJS 检测网页的背景颜色?
【发布时间】:2014-09-16 19:01:37
【问题描述】:

我正在使用 PhantomJS 使用 render() 函数对一些网页进行光栅化,有时生成的图像具有黑色背景(这应该是正常行为,如 FAQ 底部所述) .

但是如果网页没有设置背景颜色,我想设置一个白色背景只有,像这样:

page.evaluate(function() {
  if (getComputedStyle(document.body, null).backgroundColor === 'transparent') {
    document.body.bgColor = 'white';
  }
});

但它根本不起作用。我也试过:

=== 'rgba(0, 0, 0, 0)'

无济于事。

我在这里错过了什么?

【问题讨论】:

  • 你试过调试吗?在您的测试中,背景颜色是什么?您可以尝试: if (!getComputedStyle(document.body, null).backgroundColor) { ... } 如果 backgroundColor 为空、未定义、假、空字符串或任何其他“假”值,这将起作用。
  • 计算样式永远不会为 backgroundColor 返回 null、undefined、false 或空字符串。
  • 我在 'if' 条件中插入了一条 console.log() 消息,但它从未显示。顺便说一句,我在 Firefox 和 Chrome 中使用 Javascript 控制台检查了特定网页上 'getComputedStyle(document.body, null).backgroundColor' 的值,它确实返回了 'transparent'...
  • @Silas 如果你想通知一些评论员你的评论,你应该使用@replies

标签: javascript phantomjs


【解决方案1】:

请注意,某些页面可以在根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);
}

【讨论】:

    【解决方案2】:

    您可以只附加一个对 body 具有最低有用特异性 (1) 的样式元素作为 head 的第一个元素。引擎将自动使用稍后出现的背景。万一以后没有来,就用这个。

    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);
    });
    

    您也可以尝试* { background-color: white; },其特异性为 0。

    【讨论】:

    • 我尝试了您的解决方案,但背景仍然是黑色。然而,page.evaluate() 函数运行良好,因为它可以返回正确的页面标题。我不知道我做错了什么......(顺便说一句,我的测试页面是 unix.stackexchange.com)
    • 我看到背景颜色被明确设置为transparent,所以这种方法行不通。这仅在从不设置背景颜色时才有效。
    • 这给我们带来了最初的问题:如何检测背景颜色是否设置为特定值?
    • 我无法在 unix.SE 上重现您的问题,因为在 windows/linux 上的 v1.9.7 中,默认背景颜色为白色,我可以将其与 === 'rgba(0, 0, 0, 0)' 进行成功比较。我真的看不出有什么问题。你用的是什么版本?
    【解决方案3】:

    我想我找到了问题所在。其实:

    document.body.bgColor = 'white' 
    

    不起作用。我改用了:

    document.body.style.backgroundColor = '#ffffff' 
    

    现在我得到了白色背景。

    【讨论】:

    • 这并不能真正回答您检测背景颜色的原始问题。
    猜你喜欢
    • 2013-12-11
    • 2010-10-24
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    相关资源
    最近更新 更多