Dav*_*ith 12 html javascript css jquery
使用jQuery(或只是JavaScript),如何检测元素的继承背景颜色?
例如:
<div style="background-color: red">
<p id="target">I'd like to know that the background-color here is red</p>
</div>
Run Code Online (Sandbox Code Playgroud)
然而:
$('#target').css('background-color') == rgba(0,0,0,0)
Run Code Online (Sandbox Code Playgroud)
和
$('#target').css('backgroundColor') == rgba(0,0,0,0)
Run Code Online (Sandbox Code Playgroud)
我要求一般的解决方案. $('#target').parent().css('background-color')会在这种情况下工作,但不是全部.
您可以使用window.getComputedStyle()来获取继承的值。
警告:您必须在 css 或内联中手动声明继承。
#target{
background-color: inherit;
}
Run Code Online (Sandbox Code Playgroud)
工作示例:
#target{
background-color: inherit;
}
Run Code Online (Sandbox Code Playgroud)
let bgc = window.getComputedStyle($('#target')[0],null).getPropertyValue("background-color");
console.log(bgc);Run Code Online (Sandbox Code Playgroud)
#target{
background-color: inherit;
}Run Code Online (Sandbox Code Playgroud)