Parsing CSS background-image

后端 未结 2 825
有刺的猬
有刺的猬 2021-01-05 15:06

How do I parse CSS background-image, which supports multiple values, which may be none and functions (e.g. url() and linear-grad

相关标签:
2条回答
  • 2021-01-05 15:28

    Looking at the current W3C Candidate Recommendation for CSS3 (in particular, see background-image and uri), it is structured as follows:

    <background-image> = <bg-image> [ , <bg-image> ]* 
    <bg-image> = <image> | none
    <image> = <url> | <image-list> | <element-reference> | <image-combination> | <gradient>
    

    ... (you can find the rest of syntax for images here)

    EDIT:

    You will need to parse for matching parenthese or none then, and the former is not possible with regex. This post has a pseudo code for the algorithm: Python parsing bracketed blocks.

    0 讨论(0)
  • 2021-01-05 15:45
    function split (string) {
        var token = /((?:[^"']|".*?"|'.*?')*?)([(,)]|$)/g;
        return (function recurse () {
            for (var array = [];;) {
                var result = token.exec(string);
                if (result[2] == '(') {
                    array.push(result[1].trim() + '(' + recurse().join(',') + ')');
                    result = token.exec(string);
                } else array.push(result[1].trim());
                if (result[2] != ',') return array
            }
        })()
    }
    
    split("linear-gradient(top left, red, rgba(255,0,0,0)), url(a), image(url" +
          "(b.svg), 'b.png' 150dpi, 'b.gif', rgba(0,0,255,0.5)), none").toSource()
    
    ["linear-gradient(top left,red,rgba(255,0,0,0))", "url(a)",
     "image(url(b.svg),'b.png' 150dpi,'b.gif',rgba(0,0,255,0.5))", "none"]
    
    0 讨论(0)
提交回复
热议问题