div 后面有没有背景色?我想使用 js 在黑暗中获得绿色。我可以基于暗 block 位置并获得没有父级或具有 id 的父级的背景颜色吗?
<div style="background-color: #2eaa69; padding: 40px; box-sinzg: border-box width: 100%;">
<div>
<div>
<div>
<div>
<div style="background-color: #223344; padding: 20px; color: #fff; text-align: center">
get color behind this block
</div>
</div>
</div>
</div>
</div>
</div>
最佳答案
您可以访问父元素,然后从样式中获取颜色。
例如。
const b = document.querySelector("#behindthis");
console.log(b.parentElement.style.backgroundColor);
<div style="background-color: #2eaa69; padding: 40px; box-sinzg: border-box width: 100%;">
<div id="behindthis" style="background-color: #223344; padding: 20px; color: #fff; text-align: center">
get color behind this block
</div>
</div>
需要注意的一点是,如果您的样式来自 CSS,您也可以使用 getComputedStyle
。
更新:刚刚注意到 div 中的 div,等等。要在此处获取背景颜色,您可以在颜色透明时向上遍历父级。所以我更新了具有 bkColor 函数的答案。
const b = document.querySelector(".this-box");
function bkColor(b) {
const cc = window.getComputedStyle(b);
if (cc.backgroundColor === `rgba(0, 0, 0, 0)`) {
if (b.parentElement) return bkColor(b.parentElement);
}
return cc.backgroundColor;
}
console.log(bkColor(b.parentElement));
.parent-box {
background-color: #2eaa69;
padding: 40px;
}
.this-box {
background-color: #223344;
padding: 20px;
color: #fff;
text-align: center;
}
<div class="parent-box">
<div>
<div class="this-box">
get color behind this block
</div>
</div>
</div>
关于javascript - 有可能在div后面获得背景颜色吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206126/