从样式表中读取CSS属性

时间:2013-05-27 18:41:06

标签: javascript jquery html css

我正试图像这样访问css属性 -

.box{
    position:absolute;
    background-color:red;
    height:10px;
    width:10px;
}

JS:

var height = $('.box').css('height');

我知道,上面的代码是错误的,这实际上不起作用,因为.box在DOM中不可用。

我尝试的另一件事:

var height = $("<span class='box'></span>").css('height');

我的问题是:如果在课程.box的DOM中没有任何元素,我怎样才能获得box的高度?

3 个答案:

答案 0 :(得分:1)

在现代浏览器上,您可以使用document.stylesheets,并且样式表需要在原始HTML中,并且源需要与Same Origin Policy匹配,即您无法从中注入样式表Chrome扩展程序,因为它未在document.stylesheets中显示

CSS

.box {
    position:absolute;
    background-color:red;
    height:10px;
    width:10px;
}

的Javascript

function propertyFromStylesheet(selector, attribute) {
    var value;

    [].some.call(document.styleSheets, function (sheet) {
        return [].some.call(sheet.rules, function (rule) {
            if (selector === rule.selectorText) {
                return [].some.call(rule.style, function (style) {
                    if (attribute === style) {
                        value = rule.style.getPropertyValue(attribute);
                        return true;
                    }

                    return false;
                });
            }

            return false;
        });
    });

    return value;
}

console.log(propertyFromStylesheet(".box", "height"));

输出

10px

jsfiddle

答案 1 :(得分:0)

您可以在不使用DOM元素的情况下获得的唯一方法是下载样式表并解析内容。您还可以通过转到document.stylesheets并查找规则来访问已编译的样式表。您还可以使用window.getComputedStyle(element)并创建document.createElement('div')等元素,并将“.box”className附加到其中。

请记住,执行此操作意味着样式表与html文件所在的域和端口相同。

答案 2 :(得分:0)

要获取样式表中设置的元素的计算高度,它必须存在于DOM中。你可以通过创建一个元素,将它从可见屏幕上移开,然后将它附加到正文(或任何地方)来解决这个问题。

要获得高度,您可以使用.height().innerHeight()来获取没有边距和边框的高度,但包括填充:

var elem = $('<span />', {'class':'box',
                          style:'position:fixed;top:-9999px'}).appendTo('body');

var height = elem.innerHeight();

elem.remove();

FIDDLE

通常没有必要为此访问和解析样式表,除非在特殊情况下,你不是在寻找像元素高度这样的东西,而是试图检查是否在特定的特定样式中设置了样式表等。