Firefox会默默地忽略一些不合法的CSS值

时间:2012-11-28 16:56:05

标签: javascript css firefox css3

我想通过document.styleSheets获取styleSheets,但是,似乎Firefox会默默地忽略一些不合法的CSS值。我现在正在使用vh & vw,我想获取css值并为其生成正确的px。

有没有办法让Firefox忽略这些值?

1 个答案:

答案 0 :(得分:0)

我认为Firefox(可能还有其他浏览器)只返回样式表中的计算样式。

但是,您可以通过选择所需的标记进入更加手动的过程,发出ajax请求以获取其文本内容(因为它在缓存中几乎是即时的),然后解析它。

HTML:

<link rel="stylesheet" href="style.css" id="css">

js(使用jQuery):

$.get($("#css").attr("href"), function(data) //requests the css in ajax
{
   var selector = "div#right", rules = {};

   data = data.substring(data.indexOf(selector)); //trim all that is before your selector
   data = data.substring(data.indexOf("{") + 1, data.indexOf("}")); //get only what's in the curly braces
   data = data.split(";"); //split to get an array with each cell is a css rule

   for (var i = 0, l = data.length; i < l; i++) //loop through
   {
        data[i] = data[i].replace(/^\s+/, ''); //trim spaces before
        data[i] = data[i].replace(/\s+$/, ''); //trim spaces after

        if (data[i].indexOf(':') == -1) { continue; } //if rule is invalid, skip it

        data[i] = data[i].split(':'); //split rule so you have a sub-array with 0:key and 1:value
        rules[data[i][0]] = data[i][1]; //apply it to an object
   }

   console.dir(rules); //here you have. if your rules have "-" in it, you can't access with directly, but with brackets it'll be ok. ie : rules.margin-left is wrong but you can with rules["margin-left"].

}, "text");