Javascript / convert CSS style string into JS object

后端 未结 10 1034
粉色の甜心
粉色の甜心 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:18

    Stylesheet string to element style using JavaScript

    Use just the string, CSSStyleDeclaration.cssText:

    const styles = "color: black; background: orange; font-size: 2em;";
    document.querySelector("#test").style.cssText = styles;
    Lorem Ipsum

    JavaScript Implementation

    otherwise, if you need to convert a style string to Object:

    const css2obj = css => {
    	
      const r = /(?<=^|;)\s*([^:]+)\s*:\s*([^;]+)\s*/g, o = {};
      css.replace(r, (m,p,v) => o[p] = v);
      return o;
    	
    }
    
    console.log( css2obj("z-index: 4; opacity:1; transition-duration: 0.3s;") )

    In case you want to convert dash-case CSS properties to JS representations in camelCase, instead of p use p.replace(/-(.)/g, (m,p) => p.toUpperCase())


    Oldschool JS:

    function cssToObj(css) {
        var obj = {}, s = css.toLowerCase().replace(/-(.)/g, function (m, g) {
            return g.toUpperCase();
        }).replace(/;\s?$/g,"").split(/:|;/g);
        for (var i = 0; i < s.length; i += 2)
            obj[s[i].replace(/\s/g,"")] = s[i+1].replace(/^\s+|\s+$/g,"");
        return obj;
    }
    
    
    console.log( cssToObj("z-index: 4; opacity:1; transition-duration: 0.3s;") );

提交回复
热议问题