以下代码警告空字符串:
HTML:
<div id="test">test</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#test{
background-color: #f00;
}
Run Code Online (Sandbox Code Playgroud)
脚本:
alert(document.getElementById('test').style.backgroundColor)
Run Code Online (Sandbox Code Playgroud)
但是如果我在 javascript 中设置 bgcolor 那么它会提醒 bgcolor 值:
document.getElementById('test').style.backgroundColor='#ff0';
alert(document.getElementById('test').style.backgroundColor) // rgb(255,255,0)
Run Code Online (Sandbox Code Playgroud)
那么,如何获取 bgcolor 值而不在样式表中定义的 js 中设置它呢?
请注意,如果值来自用户代理的样式表而不是我的样式表,我根本不想获取值。
您看不到任何内容的原因.style是,它只提供元素上设置的样式,而不是从样式表接收的样式。
对于现代浏览器,您可以使用window.getComputedStyle来获取元素的计算样式对象。对于 IE8(以及更早的版本,但是......),您可以使用它.currentStyle来获得几乎相同的东西。所以:
var element = document.getElementById('test');
var style;
if (window.getComputedStyle) {
style = window.getComputedStyle(element);
} else {
style = element.currentStyle;
}
if (!style) {
// ...seriously old browser...
} else {
alert(style.backgroundColor);
}
Run Code Online (Sandbox Code Playgroud)
我只想获得样式表值。
getComputedStyle/currentStyle会给你这个,但也会给你浏览器的默认样式。
没有简单的界面可以仅从您自己的样式表中获取值,而不是从用户代理的默认样式表中获取值。您可能想查看document.styleSheets属性,它使您可以访问各个已解析的样式表及其规则。但是您必须处理将这些规则应用于相关元素的逻辑,这(当然)并不简单。