如何在Javascript中获取`background-color`属性值? [英] How to get `background-color` property value in Javascript?

查看:117
本文介绍了如何在Javascript中获取`background-color`属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小提琴

以下代码提醒空string:

The following code alerts empty string:

HTML:

<div id="test">test</div>

CSS:

#test{
    background-color: #f00;
}

脚本:

alert(document.getElementById('test').style.backgroundColor)

但如果我在javascript中设置bgcolor,那么它会提示bgcolor值:

But if I set bgcolor in javascript then it would alert the bgcolor value:

document.getElementById('test').style.backgroundColor='#ff0';
alert(document.getElementById('test').style.backgroundColor) // rgb(255,255,0)

那么,如何在不设置样式表中定义的js的情况下获取bgcolor值?

So, how can I get the bgcolor value without setting it in js that is defined in stylesheet?

请注意,我不想一个值,如果它来自用户代理的样式表而不是我的样式。

Note that I don't want to get a value at all if it comes from the user agent's stylesheet rather than mine.

推荐答案

你没有看到任何东西的原因 .style 只会为您提供 元素的样式,而不是从样式表中获得的样式。

The reason you're not seeing anything from .style is that that only gives you the styles set on the element, not ones it receives from stylesheets.

对于现代浏览器,您可以使用 window.getComputedStyle 获取元素的计算样式对象。对于IE8(及更早版本,但......),您可以使用 .currentStyle 获得相同的东西。所以:

For modern browsers, you can use window.getComputedStyle to get the computed style object for the element. For IE8 (and earlier, but...), you can use .currentStyle to get much the same thing. So:

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








我只想获得样式表值。

I just want to get stylesheet value.

getComputedStyle / currentStyle 会给你这个,但也会给你浏览器的默认样式。

getComputedStyle/currentStyle will give you that, but will also give you the browser's default style.

没有简单的界面只能获得来自您自己的样式表的值,而不是来自用户代理的默认样式表。您可能需要查看 document.styleSheets property ,它允许您访问各个已解析的样式表及其规则。但是你必须处理将这些规则应用于相关元素的逻辑,这当然是非常重要的。

There's no simple interface to get only the value from your own stylesheets and not from the user agent's default stylesheet. You might want to look at the document.styleSheets property, which gives you access to the individual parsed stylesheets and their rules. But you'd have to handle the logic of applying those rules to the element in question, which is (of course) non-trivial.

这篇关于如何在Javascript中获取`background-color`属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆