monic-shixi / blog

以babel开始,记录一些技术问题到issue里
2 stars 0 forks source link

js的评分实现 #10

Open monic-shixi opened 5 years ago

monic-shixi commented 5 years ago
function rater(rate) {
  return "★★★★★☆☆☆☆☆".slice(5 - rate,10 - rate);
}
rater(4)

emmmm,这也是个法子,还有其他什么好的方式吗?

monic-shixi commented 5 years ago

这里也有一个,看起来还不错,这个是怎么搞得呢?

就是通过覆盖来实现:

https://codepen.io/weixun/pen/peQmqw

 <div class="star-rating">
        <div class="star-rating-top" style="width:50%">
            <span>★</span>
            <span>★</span>
            <span>★</span>
            <span>★</span>
            <span>★</span>
        </div>
        <div class="star-rating-bottom">
            <span>★</span>
            <span>★</span>
            <span>★</span>
            <span>★</span>
            <span>★</span>
        </div>
    </div>
.star-rating {
        unicode-bidi: bidi-override;
        color: #ddd;
        font-size: 0;
        height: 25px;
        margin: 0 auto;
        position: relative;
        display: table;
        padding: 0;
        text-shadow: 0px 1px 0 #a2a2a2;
    }

    .star-rating span {
        padding: 5px;
        font-size: 20px;
    }

    .star-rating-top {
        color: #FFD700;
        padding: 0;
        position: absolute;
        z-index: 1;
        display: block;
        top: 0;
        left: 0;
        overflow: hidden;
        white-space: nowrap;
    }

    .star-rating-bottom {
        padding: 0;
        display: block;
        z-index: 0;
    }
monic-shixi commented 5 years ago

下面来个很react的方式:

https://github.com/30-seconds/30-seconds-of-react#starrating

function Star({ marked, starId }) {
  return (
    <span star-id={starId} style={{ color: '#ff9933' }} role="button">
      {marked ? '\u2605' : '\u2606'}
    </span>
  );
}

function StarRating(props) {
  const [rating, setRating] = React.useState(typeof props.rating == 'number' ? props.rating : 0);
  const [selection, setSelection] = React.useState(0);
  const hoverOver = event => {
    let val = 0;
    if (event && event.target && event.target.getAttribute('star-id'))
      val = event.target.getAttribute('star-id');
    setSelection(val);
  };
  return (
    <div
      onMouseOut={() => hoverOver(null)}
      onClick={event => setRating(event.target.getAttribute('star-id') || rating)}
      onMouseOver={hoverOver}
    >
      {Array.from({ length: 5 }, (v, i) => (
        <Star
          starId={i + 1}
          key={`star_${i + 1} `}
          marked={selection ? selection >= i + 1 : rating >= i + 1}
        />
      ))}
    </div>
  );
}