How to parse CSS font shorthand format

前端 未结 4 407
梦谈多话
梦谈多话 2021-01-11 23:19

I need to parse the CSS font shorthand format into the separate components (font-family, font-size, font-weight, ...). This shorthand format looks pretty complicated. Here a

4条回答
  •  再見小時候
    2021-01-11 23:27

    Here is my own humble try of a font parser function I just created. But I'm not sure if it works with all specialities of the font short hand format.

    function parseFont(font)
    {
        var fontFamily = null,
            fontSize = null,
            fontStyle = "normal",
            fontWeight = "normal",
            fontVariant = "normal",
            lineHeight = "normal";
    
        var elements = font.split(/\s+/);
        outer: while (element = elements.shift())
        {
            switch (element)
            {
                case "normal":
                    break;
    
                case "italic":
                case "oblique":
                    fontStyle = element;
                    break;
    
                case "small-caps":
                    fontVariant = element;
                    break;
    
                case "bold":
                case "bolder":
                case "lighter":
                case "100":
                case "200":
                case "300":
                case "400":
                case "500":
                case "600":
                case "700":
                case "800":
                case "900":
                    fontWeight = element;
                    break;
    
                default:
                    if (!fontSize)
                    {
                        var parts = element.split("/");
                        fontSize = parts[0];
                        if (parts.length > 1) lineHeight = parts[1];
                        break;
                    }
    
                    fontFamily = element;
                    if (elements.length)
                        fontFamily += " " + elements.join(" ");
                    break outer;
            }
        }
    
        return {
            "fontStyle": fontStyle,
            "fontVariant": fontVariant,
            "fontWeight": fontWeight,
            "fontSize": fontSize,
            "lineHeight": lineHeight,
            "fontFamily": fontFamily
        }
    }
    

提交回复
热议问题