如何确定可见底层元素的背景颜色?

时间:2016-02-16 21:19:01

标签: jquery html css

我有一个固定位置的页面'go to top'<a>,当用户滚动时,它会粘在页面底部。它位于页面的页脚DIV中,如下所示:

.pagedown div a { position: fixed; margin-left: 8px;  margin-top: 50px; width: 44px; height: 40px; color: #bd1300; background: none;}

<div class="footer"><a id="gototop" title="Go to top!" href="#">^</a></div>

使用jQuery或JS我希望能够根据真实的底层背景颜色更改<a>的颜色。到目前为止,我看过这里:

How do I detect the inherited background-color of an element using jQuery/JS?

此代码似乎不适用于我的用例。也许是因为有问题的<a>在页面DOM的其余部分内部并不是真正“滚动”?

那么:有没有办法检测-true-底层背景颜色(即用户在视口中实际看到的背景颜色)?

2 个答案:

答案 0 :(得分:3)

支持不是很好(没有IE),但你可以使用CSS。

mix-blend-mode @ MDN

.footer {
  font-size: 72px;
  text-align: center;
  margin-bottom: 10px;
  line-height: 100px
}
a {
  color: white;
  mix-blend-mode: difference;
}
body {
  background: red;
}
<div class="footer"><a class="gototop" title="Go to top!" href="#">^</a>
</div>

.footer {
  font-size: 72px;
  text-align: center;
  margin-bottom: 10px;
  line-height: 100px
}
a {
  color: white;
  mix-blend-mode: difference;
}
body {
  background: blue;
}
<div class="footer"><a class="gototop" title="Go to top!" href="#">^</a>
</div>

答案 1 :(得分:0)

您正在寻找window.getComputedStyle

它返回你给它的元素的计算样式。

编辑:背景颜色属性返回透明,因此我编写了一个递归背景颜色搜索功能,可以避免此行为。

function getBGColor(el) {
    var s = getComputedStyle(el),
        b = s.backgroundColor,
        e = el;
    if ((b === "transparent" || b === "rgba(0, 0, 0, 0)" || b === "rgba(255,255,255,0)") && e.parentNode !== null)
        b = getBGColor(e.parentNode);
    return b;
}

document.getElementById("o").innerHTML = "Background Color: " + getBGColor(document.getElementById('gototop'));
html,
body {
  background-color: lavender;
}
a {
  color: #bd1300;
}
<div>
  <a id="gototop" title="Go to top!" href="#">^</a>
</div>

<div id="o"></div>