Star Rating with SVG catering for decimal point rating

前端 未结 3 637
南旧
南旧 2021-01-17 05:38

I have some code to create a star rating. I have not used SVG before and I can\'t figure out how to get it to do the following:

  • Rating is out of 5
  • Di
相关标签:
3条回答
  • 2021-01-17 06:22

    Here is Fiddle with dots: http://jsfiddle.net/cnLHE/296/

    You can place a rectangle underneath masked elements. In this Fiddle, the rectangle is width=90, which is 90% (at very bottom).

    <rect x="0" y="0" width="90" height="20" style="fill:#2498c7; mask: url(#mask5)"/>
    

    Change the 90 to 55, for example, and the underlying fill will shrink width.

    Warning: I scrapped this method, because it did not work well with 20+ instances in page. For example, when loading a grid of rated products, the ratings graphic would sometimes disappear in Chrome. JS methods were more reliable.

    0 讨论(0)
  • 2021-01-17 06:31

    Change the offset fields from 0 (unfilled) to 1 (filled) to move the rating.

    Not sure why you're specifying red in two different ways or why you've slightly different offset values.

    0 讨论(0)
  • 2021-01-17 06:36

    You can adjust the <linearGradient> with some simple JS. Example below.

    function setFraction(fraction)
    {
        document.getElementById("stop1").setAttribute("offset", fraction);
        document.getElementById("stop2").setAttribute("offset", fraction);
    }
    
    
    setFraction(0.4);
    <svg height="210" width="500">
      <polygon points="165.000, 185.000, 188.511, 197.361, 184.021, 171.180,
     203.042, 152.639,
     176.756, 148.820,
     165.000, 125.000,
     153.244, 148.820,
     126.958, 152.639,
     145.979, 171.180,
     141.489, 197.361,
     165.000, 185.000" style="stroke:red; fill:url(#g)"/>
      <linearGradient id="g" x1="0" y1="0" x2="1" y2="0">
        <stop id="stop1" stop-color="#F00" offset="0.5"/>
        <stop id="stop2" stop-color="#fff" offset="0.5"/>
      </linearGradient>
    </svg>

    If you wanted to avoid JS, then you could create 11 different versions of the star (unfilled, 0.1, 0.2 ... 0.9, filled) and just include the correct one.

    0 讨论(0)
提交回复
热议问题