萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 五星評分插件 Star Rating 完整示例與原理解析

效果預覽

鼠標懸停顯示高亮星星,點擊鎖定評分,支持半星(0.5 步長),可編輯/只讀模式切換,提交時獲取數值。

完整 HTML + CSS + JS 代碼

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery 五星評分插件</title>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
  <script src="js/star_rating.js"></script> <!-- 插件核心 -->
  <style>
    #rating_cont { background:#1E1D1C url(images/rating_background.jpg) no-repeat; border:1px solid #F9BA0D; width:140px; height:23px; text-align:left; margin-left:6px; }
    #rating_on { background:url(images/rating_onbackground.jpg) no-repeat; width:0; height:21px; position:relative; z-index:50; top:-21px; }
    #rated { display:none; width:138px; padding:3px 0 3px 2px; height:23px; background:#1E1D1C; font-size:11px; color:#FFC910; }
    #rated div { display:block; float:left; }
    #rating { font-size:11px; font-family:Arial; color:#FFC910; padding-left:3px; width:22px; }
    #small_stars { height:11px; width:69px; background:url(images/stars_small_sprite.jpg) 0 -11px; font-size:1px; line-height:11px; margin-top:3px; }
    #rate_edit { line-height:17px; font-size:11px; font-family:Arial; color:#FFF; padding-left:9px; cursor:pointer; }
    #rate_edit:hover { text-decoration:underline; }
    #rating_btns { position:relative; z-index:100; width:140px; height:21px; }
    #rating_btns ul, #rating_btns li { padding:0; margin:0; }
    #rating_btns li { float:left; width:14px; height:21px; display:block; font-size:1px; cursor:pointer; color:#1E1D1C; }
  </style>
</head>
<body>
  <div id="demo">
    <div id="rating_cont">
      <div id="rating_btns">
        <ul>
          <li>0.5</li><li>1.0</li><li>1.5</li><li>2.0</li><li>2.5</li>
          <li>3.0</li><li>3.5</li><li>4.0</li><li>4.5</li><li>5.0</li>
        </ul>
      </div>
      <div id="rating_on"></div>
      <div id="rated">
        <div id="rating" style="height:17px;line-height:17px;">not rated</div>
        <div> - </div>
        <div id="small_stars"></div>
        <div id="rate_edit">edit</div>
      </div>
    </div>
    <input type="hidden" id="rating_output" name="rating_output" value="not rated" />
  </div>
</body>
</html>

插件核心邏輯解析 (star_rating.js 關鍵點)

;(function($) {
  $.fn.rating = function(options) {
    var opts = $.extend({ step: 0.5, readonly: false, callback: null }, options);
    return this.each(function() {
      var $container = $(this);
      var $btns = $container.find('#rating_btns li');
      var $on = $container.find('#rating_on');
      var $rating = $container.find('#rating');
      var $small = $container.find('#small_stars');
      var $edit = $container.find('#rate_edit');
      var $output = $('#rating_output');

      // 懸停高亮
      $btns.hover(function() {
        if (opts.readonly) return;
        var idx = $btns.index(this);
        var width = (idx + 1) * 14; // 每顆星 14px
        $on.stop().animate({width: width}, 100);
        $rating.text($(this).text());
      }, function() {
        if (opts.readonly) return;
        // 恢復當前值
        var val = parseFloat($output.val()) || 0;
        var width = (val / opts.step) * 14;
        $on.stop().animate({width: width}, 100);
        $rating.text(val || 'not rated');
      });

      // 點擊鎖定
      $btns.click(function() {
        if (opts.readonly) return;
        var val = parseFloat($(this).text());
        $output.val(val);
        $rating.text(val);
        $small.css('background-position', '0 0'); // 顯示實心小星
        if (opts.callback) opts.callback(val);
      });

      // 編輯模式切換
      $edit.click(function() {
        opts.readonly = !opts.readonly;
        $(this).text(opts.readonly ? 'edit' : 'save');
        $btns.css('cursor', opts.readonly ? 'default' : 'pointer');
      });

      // 初始化
      var initVal = parseFloat($output.val()) || 0;
      if (initVal) {
        var w = (initVal / opts.step) * 14;
        $on.width(w);
        $rating.text(initVal);
      }
    });
  };
})(jQuery);

// 初始化調用
$(function() {
  $('#rating_cont').rating({
    step: 0.5,
    callback: function(val) { console.log('評分提交:', val); }
  });
});

關鍵 CSS Sprite 技巧

  • #rating_on 寬度動畫實現「填滿」效果,背景圖為亮星圖。
  • #small_stars 使用 background-position: 0 -11px 顯示空心星,0 0 顯示實心星,單圖多狀態。
  • 每個 li 寬 14px,對應 0.5 分步長,10 顆星 = 5 分滿分。

現代替代:原生 CSS/JS 實現(無依賴)

<style>
.stars { display: inline-flex; direction: rtl; font-size: 1.5rem; }
.stars input { display: none; }
.stars label { cursor: pointer; color: #ccc; transition: color .2s; }
.stars input:checked ~ label, .stars label:hover, .stars label:hover ~ label { color: #ffc107; }
</style>

<div class="stars">
  <input type="radio" id="s5" name="rating" value="5"><label for="s5">★</label>
  <input type="radio" id="s4" name="rating" value="4"><label for="s4">★</label>
  <input type="radio" id="s3" name="rating" value="3"><label for="s3">★</label>
  <input type="radio" id="s2" name="rating" value="2"><label for="s2">★</label>
  <input type="radio" id="s1" name="rating" value="1"><label for="s1">★</label>
</div>

純 CSS 實現:利用 direction: rtl + 兄弟選擇器 ~ 實現懸停/選中高亮,無需任何 JS,極輕量。

總結

jQuery Star Rating 插件通過 CSS Sprite + 寬度動畫實現平滑半星評分,適合老項目維護。新項目強烈推薦純 CSS 方案或成熟組件庫(RateYo、Vue-Star-Rating、React-Rate),功能更全、無 jQuery 依賴。

copyright © 萬盛學電腦網 all rights reserved