萬盛學電腦網

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

原生 JavaScript 實現星星評分交互:懸停點亮、點擊定分、文字提示三態聯動

交互邏輯

  1. 懸停某顆星 → 該星及之前所有星點亮(高亮),顯示對應評價文字
  2. 移出 → 恢復灰色,文字隱藏
  3. 點擊 → 固定評分,顯示「X 分」結果

HTML + CSS

<style>
  .wrapper { width: 300px; margin: 10px auto; font: 14px/1.5 Arial; }
  #star { overflow: hidden; }
  #star li {
    float: left; width: 20px; height: 20px; margin: 2px;
    display: inline; color: #999; font: bold 18px Arial; cursor: pointer;
  }
  #star .act { color: #c00; } /* 高亮色 */
  #star_word {
    width: 80px; height: 30px; line-height: 30px;
    border: 1px solid #ccc; margin: 10px auto; text-align: center; display: none;
  }
</style>

<div class="wrapper">
  評分結果 <span id="result"></span>
  <ul id="star">
    <li>★</li><li>★</li><li>★</li><li>★</li><li>★</li>
  </ul>
  <div id="star_word">一般</div>
</div>

JS 邏輯實現

window.onload = function() {
  var stars = document.getElementById('star').getElementsByTagName('li');
  var wordBox = document.getElementById('star_word');
  var resultBox = document.getElementById('result');
  var texts = ['很差', '差', '一般', '好', '很好'];
  var len = stars.length;
  var lockedIndex = -1; // 已鎖定的評分

  for (var i = 0; i < len; i++) {
    stars[i].index = i;

    stars[i].onmouseover = function() {
      if (lockedIndex !== -1) return; // 已鎖定則不響應懸停
      wordBox.style.display = 'block';
      wordBox.innerHTML = texts[this.index];
      for (var j = 0; j <= this.index; j++) stars[j].className = 'act';
    };

    stars[i].onmouseout = function() {
      if (lockedIndex !== -1) return;
      wordBox.style.display = 'none';
      for (var j = 0; j < len; j++) stars[j].className = '';
    };

    stars[i].onclick = function() {
      lockedIndex = this.index;
      resultBox.innerHTML = (this.index + 1) + '分';
      wordBox.style.display = 'none';
    };
  }
};

進階擴展建議

  • 半星支援:每顆星拆分為左右兩半,mousemove 計算偏移量決定半星高亮。
  • 提交後端:click 時 AJAX 發送 {score: lockedIndex+1}。
  • 只讀模式:直接根據後端返回分數渲染 .act,移除事件綁定。
  • 無障礙:添加 role="radio"、aria-label、鍵盤左右鍵操作。
copyright © 萬盛學電腦網 all rights reserved