从样式表中读取CSS属性 [英] read CSS property from stylesheet

查看:111
本文介绍了从样式表中读取CSS属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试访问像这样的css属性 -

  .box {
position:absolute;
背景颜色:红色;
height:10px;
width:10px;

JS:

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

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



另一件我试过的:

<$ pss('height'); p $ p> var height = $(< span class ='box'>< / span>)。

我的问题是:如何获得 .box 没有任何元素在DOM中,类为 box

解决方案

在现代浏览器上,您可以使用 document.stylesheets ,样式表需要在原始的HTML中,并且源代码需要匹配相同原产地政策,即您不能从Chrome扩展插入样式表,因为它不会在document.stylesheets中显示


$ b

CSS

  .box {
position:absolute;
背景颜色:红色;
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;
});
}

返回false;
});
});

返回值;


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

输出

  10px 

jsfiddle


I am trying to access css property like this -

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

JS:

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

i know, above code is wrong and this actually doesn't work as .box is not available in DOM.

Another thing that i tried :

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

My question is: how can i get height of .box without having any element in DOM with class box ?

解决方案

On a modern browser you could use document.stylesheets, and the stylesheet would need to be in the original HTML and the source needs to match the Same Origin Policy, i.e. you can't inject the stylesheet from say a Chrome extension as it does not show in 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"));

Output

10px

On jsfiddle

这篇关于从样式表中读取CSS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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