Javascript / convert CSS style string into JS object

后端 未结 10 980
粉色の甜心
粉色の甜心 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条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 09:16

    Just for fun and for completeness…

    I haven't checked cross-browser compatibility (only tried in Chrome), and it has some quirks:

    var input = "font-weight:bold; color: blue; margin: 0 15px";
    
    var e = document.createElement("div");
    e.setAttribute("style", input);
    
    var output = {};
    
    for (var i = 0; i < e.style.length; i++) {
      var name = e.style[i];
      var value = e.style.getPropertyValue(name);
      output[name] = value;
    }
    

    The quirk is that even though we passed in a single margin declaration, we get an object like

    {
      color: "blue",
      font-weight: "bold",
      margin-bottom: "0px",
      margin-left: "15px",
      margin-right: "15px",
      margin-top: "0px",
    }
    

    This might be a good or a bad thing depending on what you're after.

提交回复
热议问题