【问题标题】:Problem while converting javascript object into css styles将javascript对象转换为css样式时出现问题
【发布时间】:2019-09-24 06:34:15
【问题描述】:

我正在尝试将 javascript 转换为 css 样式,我能够转换为 css 格式,但是,出现了问题。我无法删除双引号 "' 符号。

var out =  console.log, 
    a   =  {
      ".time":{
        "color":"red",
        'background-color':'yellow',
         height:'10%',
         zindex:1
      },
      '#next':{
        'colour':'#eee'
      },
      div:{
        width:10,
        '-webkit-hyphenate-character': 'auto'
      },
      "@keyframes example" : {
          "0%" :  {"background-color": 'red'},
          "25%" :  {"background-color": 'yellow'}
       }
    }

var toStyles = function(object){
  var store = '';
  Object.keys(object).forEach(name => {
       var value = object[name];
       if(typeof value == 'object'){
         
       }
       var style = name+':'+JSON.stringify(value)+';';
       store = store + style;
  });
  console.log(store)
}

toStyles(a)

我的输出:-

.time{
       "color":"red",
       "background-color":"yellow",
        "height":"10%",
        "zindex":1
     };

#next{
     "colour":"#eee"
 };

div{
    "width":10,
    "-webkit-hyphenate-character":"auto"
};
@keyframes example{
    "0%":{"background-color":"red"},
    "25%":{"background-color":"yellow"}
};

如何将这样的对象转换为正确的 css 样式。

请帮帮我

【问题讨论】:

标签: javascript css object


【解决方案1】:

您可以使用正则表达式将每个 " 替换为空字符串

但是您仍然会遇到其他问题,您将 css 规则与 , 分开,这应该是 ; 并且您在不应该存在的选择器之后添加 :

你可以用这个替换你的代码,它应该可以工作

var style = name+' '+JSON.stringify(value).replace(/"/g,'').replace(/,/g,'; ')+'\n';

var a   =  {
      ".time":{
        "color":"red",
        'background-color':'yellow',
         height:'10%',
         zindex:1
      },
      '#next':{
        'colour':'#eee'
      },
      div:{
        width:10,
        '-webkit-hyphenate-character': 'auto'
      },
      "@keyframes example" : {
          "0%" :  {"background-color": 'red'},
          "25%" :  {"background-color": 'yellow'}
       }
    }

var toStyles = function(object){
  var store = '';
  Object.keys(object).forEach(name => {
       var value = object[name];
       if(typeof value == 'object'){

       }
       var style = name+' '+JSON.stringify(value).replace(/"/g,'').replace(/,/g,'; ')+'\n';
       store = store + style;
  });
  console.log(store)
}

toStyles(a)

【讨论】:

  • 我猜属性值包含 " 请正确查看输出。
  • 你指的是哪个输出?我的输出中没有 "
【解决方案2】:

这应该可以帮助您入门,但请注意它不处理嵌套属性(例如 keyframes),但是添加为递归调用很简单。

let input = {
  ".time": {
    "color": "red",
    'background-color': 'yellow',
    height: '10%',
    zindex: 1
  },
  '#next': {
    'colour': '#eee'
  },
  div: {
    width: 10,
    '-webkit-hyphenate-character': 'auto'
  },
  "@keyframes example": {
    "0%": {"background-color": 'red'},
    "25%": {"background-color": 'yellow'}
  }
};

let output = Object.entries(input).map(([selector, properties]) => `${selector} {\n${Object.entries(properties).map(([name, value]) => `\t${name}: "${value}";`).join('\n')}\n}`).join('\n\n');

console.log(output);

【讨论】:

  • @keyframes example { 0%: "[object Object]"; 25%: "[object Object]"; } 你的问题是。 [对象对象]…
【解决方案3】:

我也在寻找同样的东西感谢发布这个问题。这可以处理您在问题中提到的所有内容。

    var a   =  {
      'div':{
        "width": "100px",
        "height": "100px",
        "background": "red",
        "position": "relative",
        "-webkit-animation": "mymove 5s infinite", 
        "animation": "mymove 5s infinite"
      },
      '@-webkit-keyframes mymove':{
         '0%':{'top': '0px;'},
         '25%':{'top': '200px;'},
         '75%':  {'top': '50px'},
         '100%': {'top': '100px'},
      },
      '@keyframes mymove':{
        '0%'   :  {'top': '0px'},
        '25%'  :  {'top': '200px'},
        '75%'  :  {'top': '50px'},
        '100%' : {'top': '100px'}
      }
    }

    String.prototype.replaceAt=function(index, replacement) {
       return this.substr(0, index) + replacement+ this.substr(index + 
       replacement.length);
    }

   var indexes = function(string , char){
      var result = []; 
      for(var i = 0 ; i < string.length ; i++ ){
         var pos1 = string.substr( i , char.length);
         if(pos1 == char){
           result.push(i)
         }
      }
      return(result)
    }

    var maker = function(value){
        var a     =  JSON.stringify(value).replace(/"/g,'').replace(/,/g,'; '),
            index =  indexes(a,'%:')
            index2 =  indexes(a,'};');

        if(index && index.length > 0){
           for(var i  = 0 ; i < index.length ; i++){
             a = a.replaceAt(index[i]+1, " "); 
           }
         }
         if(index2 && index2.length > 0){
           for(var i  = 0 ; i < index2.length ; i++){
             a = a.replaceAt(index2[i]+1,' '); 
           }
         }
         return a;
    };

    var toStyles = function(object){
       var store = '';
       Object.keys(object).forEach(name => {
          var value = object[name];
          var style = name+' '+maker(value)+'\n';
           store = store + style;
       });
       return(store)
    }

    console.log(toStyles(a))

我已经为这个问题的未来进展创建了 github 存储库,请做出贡献以使其更好地处理各种转换。

Github Repo for this Problem

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2017-05-09
    • 2020-07-10
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2019-10-16
    相关资源
    最近更新 更多