简体   繁体   English

将javascript对象转换为CSS样式时出现问题

[英]Problem while converting javascript object into css styles

I am trying to convert javascript into css styles , I was able to convert into css format but , There was problem . 我正在尝试将javascript转换为css样式,我能够将其转换为css格式,但是出现问题。 I was unable to remove double quort " or ' symbol. 我无法删除符号。

 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) 

My output:- 我的输出:-

.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"}
};

How can i convert objects like this into proper css styles. 我如何将这样的对象转换为适当的CSS样式。

Please Help me 请帮我

I was also looking for same thing thanks for posting this question . 我也一直在寻找相同的东西,谢谢你发布这个问题。 This can handle everything you want that you have mentioned on your question. 这可以处理您在问题中提到的所有内容。

    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))

I have created github repo for future progress for this problem please contribute to make it more better that can handle every kind to transformation. 我已经为这个问题的未来进展创建了github repo,请做出贡献以使其更好地处理各种转换。

Github Repo for this Problem Github仓库为此问题

you can use regex to replace every " with an empty string 您可以使用正则表达式将每个"替换为空字符串

but you will still have other problems, you are separating css rules with , which should be ; 但是您仍然会有其他问题,您正在使用分隔CSS规则,应该是; and you add : after the selector which shouldn't be there 然后在选择器后面添加:

you can replace your code with this, and it should work 您可以用它替换您的代码,它应该可以工作

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) 

This should get you started, but note it doesn't handle nested properties (eg keyframes ), but that's trivial to add on as a recursive call. 这应该使您入门,但是请注意,它不处理嵌套的属性(例如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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM