Javascript / convert CSS style string into JS object

后端 未结 10 1068
粉色の甜心
粉色の甜心 2021-01-04 08:41

We\'d like to convert a CSS style entered as string into a JS object.

E.g.,

 var input = \" border:solid 1px; color:red \";

expec

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 08:54

    You could use the Javascript split function: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

    First split the string with ; as the separator, and then for each result split with :, placing the items in an object as you go.

    e.g.

    var result = {},
        attributes = input.split(';');
    
    for (var i = 0; i < attributes.length; i++) {
        var entry = attributes[i].split(':');
        result[entry.splice(0,1)[0]] = entry.join(':');
    }
    

提交回复
热议问题