萬盛學電腦網

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

jQuery 實現淘寶風格星星評分組件(含半星、只讀模式)

效果預覽

鼠標懸停高亮對應星星,點擊鎖定評分,支持半星、只讀展示、獲取分數回調。

星星評分效果圖

HTML 結構

<div id="starRating" data-score="0" data-readonly="false">
  <ul class="stars">
    <li data-value="1">☆</li>
    <li data-value="2">☆</li>
    <li data-value="3">☆</li>
    <li data-value="4">☆</li>
    <li data-value="5">☆</li>
  </ul>
  <input type="hidden" name="rating" value="0">
  <span class="score-text">0 分</span>
</div>

CSS 樣式

.stars { list-style: none; padding: 0; margin: 0; display: flex; gap: 4px; }
.stars li { font-size: 28px; color: #ddd; cursor: pointer; transition: color 0.2s; user-select: none; }
.stars li.hover, .stars li.active { color: #ffc107; } /* 高亮/選中金黃 */
.stars li.half::before { content: '★'; position: absolute; width: 50%; overflow: hidden; color: #ffc107; } /* 半星 */
.readonly .stars li { cursor: default; }
.score-text { margin-left: 12px; font-size: 14px; color: #666; }

jQuery 核心邏輯

(function($) {
  $.fn.starRating = function(options) {
    var settings = $.extend({
      max: 5,
      step: 1,           // 1 = 整星, 0.5 = 半星
      readonly: false,
      initialScore: 0,
      onChange: function(score) {} // 回調
    }, options);

    return this.each(function() {
      var $container = $(this);
      var $stars = $container.find('.stars li');
      var $input = $container.find('input[type="hidden"]');
      var $text = $container.find('.score-text');
      var currentScore = settings.initialScore;

      // 初始化
      render(currentScore);

      if (settings.readonly) {
        $container.addClass('readonly');
        return;
      }

      // 懸停高亮
      $stars.on('mouseenter', function() {
        var val = $(this).data('value');
        highlight(val);
      });

      // 移出恢復
      $stars.on('mouseleave', function() {
        render(currentScore);
      });

      // 點擊鎖定
      $stars.on('click', function() {
        currentScore = $(this).data('value');
        $input.val(currentScore);
        render(currentScore);
        settings.onChange.call(this, currentScore);
      });

      // 內部函數
      function highlight(score) {
        $stars.each(function() {
          var $li = $(this);
          var val = $li.data('value');
          if (val <= score) {
            $li.removeClass('hover half').addClass('hover');
          } else if (settings.step === 0.5 && val - 0.5 === score) {
            // 半星處理:下一顆星顯示半滿
            $li.removeClass('hover').addClass('hover half');
          } else {
            $li.removeClass('hover half');
          }
        });
        $text.text(score + ' 分');
      }

      function render(score) {
        $stars.each(function() {
          var $li = $(this);
          var val = $li.data('value');
          $li.removeClass('active half hover');
          if (val <= score) {
            $li.addClass('active');
          } else if (settings.step === 0.5 && val - 0.5 === score) {
            $li.addClass('active half');
          }
        });
        $text.text(score + ' 分');
      }

      // 對外暴露方法
      $container.data('starRating', {
        setScore: function(s) { currentScore = s; $input.val(s); render(s); },
        getScore: function() { return currentScore; },
        setReadonly: function(ro) { settings.readonly = ro; $container.toggleClass('readonly', ro); }
      });
    });
  };
})(jQuery);

使用示例

// 基礎用法
$('#starRating').starRating({
  initialScore: 3,
  onChange: function(score) {
    console.log('用戶評分:', score);
    // 可在此 AJAX 提交
  }
});

// 半星模式
$('#starRatingHalf').starRating({ step: 0.5, initialScore: 3.5 });

// 只讀展示
$('#starRatingReadonly').starRating({ readonly: true, initialScore: 4.5 });

// 程式化控制
var api = $('#starRating').data('starRating');
api.setScore(2);
console.log(api.getScore());

進階擴展建議

  • 使用 SVG 圖標替代 Unicode 星號,顯示更銳利、可著色。
  • 添加鍵盤無障礙支持(tabindex、keydown 左右鍵調整)。
  • 整合至表單驗證庫(如 jQuery Validate)。
  • 服務端渲染初始分數時,直接輸出 data-initial-score 供 JS 讀取。
copyright © 萬盛學電腦網 all rights reserved