我正在尝试将 javascript 转换为 css 样式,我能够转换为 css 格式,但是出现了问题。我无法删除 double quort " 或 ' 符号。
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 样式。
请帮帮我
最佳答案
我也在寻找同样的东西感谢您发布这个问题。这可以处理您在问题中提到的所有问题。
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))
我已经为这个问题的 future 进展创建了 github 存储库,请做出贡献,让它变得更好,可以处理各种转换。
关于javascript - 将javascript对象转换为css样式时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56008323/