Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将css字符串转换为数组_Javascript_Jquery - Fatal编程技术网

Javascript 如何将css字符串转换为数组

Javascript 如何将css字符串转换为数组,javascript,jquery,Javascript,Jquery,这就是我要做的。 我想转换一个包含CSS规则的数组,如下所示: [ ".divd { bottom: 0px; height: 500px; }" , ".divk { font-size: 14px; }" ] 我想把它变成: cssarray['divd'] = { bottom: "0px", height: "500px", }; 以下是我迄今为止所做的工作: var splitSelector= css.split("{"

这就是我要做的。 我想转换一个包含CSS规则的数组,如下所示:

[

".divd { bottom: 0px; height: 500px; }"

, 

".divk { font-size: 14px; }"

]
我想把它变成:

cssarray['divd'] =  {
        bottom: "0px",
        height: "500px",
    };
以下是我迄今为止所做的工作:

    var splitSelector= css.split("{");
    var splitProperty = split[1].split(";");
    var v =[];
    for(i in splitProperty ){
        v = $.extend(v,splitProperty[i].split(":"));
    }
我曾试图用大量的拆分语句来完成这项工作,但我运气不好。

看看这把小提琴:

日志:

Object
    divd: Object
        bottom: "0px"
        height: "500px"
    divk: Object
        font-size: "14px"

我不是eval的支持者,但是如果你改变

。到[

第一个空格至]=

:致:

);对,


然后eval将设置整个过程

不幸的是,解析CSS标记并不像拆分字符串那么容易,事实上,理想情况下,您需要一个解析器,我建议在您的任务中使用现有的CSS解析器:

一种无RegExp方法

var cssObj = {},
    arr = [".divd { bottom: 0px; height: 500px; }", ".divk { font-size: 14px; }"],
    arr_i = arr.length,
    i, j, k, str,
    sel, vals, val;
while(arr_i-- > 0){       // loop over array
    str = arr[arr_i];
    i = str.indexOf('{');
    sel = str.slice(0,i); // get Selector
    vals = str.slice(i+1,str.lastIndexOf('}'));           // get values
    val = vals.slice(0,vals.lastIndexOf(';')).split(';'); // and put in array
    cssObj[sel] = {};
    k = val.length;
    while(k-- > 0){
        j = val[k].indexOf(':');                      // get name-value pair
        cssObj[sel][val[k].slice(0,j).trim()] = val[k].slice(j+1).trim();
    }
}
console.log(cssObj); // see output
要用作函数,请传递arr并更改console.log以返回。.slice0,vals.lastIndexOf';'假设以分号结尾}前面的最后一个条目。如果您不想假设这一点,请将其取出并检查最后一个数组项是否为空/空白


我在过去使用过这个,但只有在我确切地知道我将要发送到regexp中的内容时——主要是因为我确信会有语法打破它,特别是对于mixin、css动画、css变量和媒体查询。正是因为这些原因,你才应该遵循马里奥的答案

然而,它已经在我自己的大部分css文件上工作了,我已经抛出了它,可能会帮助其他人在那里。。。不过,它并不是专门为处理您正在使用的阵列结构而定制的,但这很容易改变。很明显,您可以通过摆脱RegExp并像shhac那样使用indexOf来优化事情,但我发现RegExp的表达能力更容易使用,并且在需要时更容易扩展

一些注释

它假定CSS中没有注释-您可以始终添加替换以删除注释。 它依赖于可用的JSON.parse方法——您可以始终包含非JSON回退。 带注释的代码:

window.onload = function(){
  /// this is designed to find a <style> element in the page with id="css"
  var entireStylesheetString = document.getElementById('css').innerHTML;
  var css = String('{'+entireStylesheetString+'}')
    /// convert double quotes to single to avoid having to escape
    .replace(/"/gi,"'")
    /// replace all whitespace sequences with single space
    .replace(/\s+/g,' ')
    /// sort the first open brace so things are neat
    .replace(/^{/,'{\n')
    /// sort the newlines so each declaration is on own line
    .replace(/\}/g,'}\n')
    /// find the selectors and wrap them with quotes for JSON keys
    .replace(/\n\s*([^\{]+)\s+?\{/g,'\n"$1":{')
    /// find an attribute and wrap again with JSON key quotes
    .replace(/([\{;])\s*([^:"\s]+)\s*:/g,'$1"$2":')
    /// find values and wrap with JSON value quotes
    .replace(/":\s*([^\}\{;]+)\s*(;|(\}))/g,'":"$1",$3')
    /// add commas after each JSON object
    .replace(/\}/g,'},')
    /// make sure we don't have too many commas
    .replace(/,\s*\}/g,'}');
  /// remove the final end comma
  css = css.substring(0,css.length-2);
  try{
    /// parse using JSON
    console.log(JSON.parse(css));
  }catch(ee){
    console.log(ee);
  }
};

您可以简单地附加一个样式标记

var data=[".divd { bottom: 0px; height: 500px; }", 
".divk { font-size: 14px; }"
]

var $style=$('<style>');

$.each( data, function(i, item){
  $style.append( item + ';');
})

$('head').append($style)

您的代码只处理css类的规则。。。您的cssarray如何查找div.divd选择器?会是cssarray['div.divd']吗?它现在有一个“divd”键,这意味着它忽略了选择器中的前一个点。我真的非常感谢您的辛勤工作,非常感谢。。。但问题是,如果选择器是一个id选择器,那么它就不起作用了:不管这对类选择器有多好,它应该做什么。。。再次感谢:
window.onload = function(){
  var entireStylesheetString = document.getElementById('css').innerHTML;
  var css = String('{'+entireStylesheetString+'}')
    .replace(/"/gi,"'")
    .replace(/\s+/g,' ')
    .replace(/^{/,'{\n')
    .replace(/\}/g,'}\n')
    .replace(/\n\s*([^\{]+)\s+?\{/g,'\n"$1":{')
    .replace(/([\{;])\s*([^:"\s]+)\s*:/g,'$1"$2":')
    .replace(/":\s*([^\}\{;]+)\s*(;|(\}))/g,'":"$1",$3')
    .replace(/\}/g,'},')
    .replace(/,\s*\}/g,'}');
  css = css.substring(0,css.length-2);
  try{console.log(JSON.parse(css));}catch(ee){console.log(ee);}
};
var data=[".divd { bottom: 0px; height: 500px; }", 
".divk { font-size: 14px; }"
]

var $style=$('<style>');

$.each( data, function(i, item){
  $style.append( item + ';');
})

$('head').append($style)