萬盛學電腦網

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

JavaScript 實現鼠標懸停星級評分:即時預覽與離開重置

核心邏輯

function ArrayIndexof(arr, el) {
    for (var i = 0; i < arr.length; i++) if (arr[i] == el) return i;
    return -1;
}

function GetTDS() {
    return document.getElementById("tblMain").getElementsByTagName("td");
}

function iniEvent() {
    var tds = GetTDS();
    for (var i = 0; i < tds.length; i++) {
        tds[i].onmouseover = TdOnMouseOver;
    }
    document.getElementById("tblMain").onmouseout = TableMouseOut;
}

function SetRating(tdTmp) {
    var tds = GetTDS();
    var index = ArrayIndexof(tds, tdTmp);
    for (var i = 0; i <= index; i++) tds[i].innerHTML = "★";
    for (var i = index + 1; i < tds.length; i++) tds[i].innerHTML = "☆";
}

function TdOnMouseOver() { SetRating(this); }
function TableMouseOut() { GetTDS().forEach(td => td.innerHTML = "☆"); }

關鍵設計

  1. 懸停預覽:onmouseover 觸發,根據索引將當前及之前星星填滿(★),之後置空(☆)。
  2. 離開重置:table.onmouseout 捕獲鼠標離開表格區域,全部重置為 ☆。
  3. 索引查找:ArrayIndexof 將 HTMLCollection 視為數組查找位置。

缺陷與改進

  • 無點擊鎖定:離開即重置,無法保存評分。需增加 onclick 記錄選中值,onmouseout 時恢復到已選狀態。
  • innerHTML 覆蓋:直接改星號字符,若星星包含其他結構會丟失。建議用 className 切換樣式。
  • 事件委託優化:單綁 table.onmouseover,用 e.target.closest('td') 判斷。

現代純 CSS 方案(推薦)

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

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

無 JS、語義化、鍵盤可訪問、表單原生提交值。

JS 增強版(含鎖定)

class StarRating {
    constructor(container, max = 5) {
        this.container = container;
        this.max = max;
        this.value = 0;
        this.render();
        this.bind();
    }
    render() {
        this.container.innerHTML = '';
        this.stars = [];
        for (let i = this.max; i >= 1; i--) {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.dataset.value = i;
            btn.textContent = '★';
            btn.setAttribute('aria-label', `${i} 星`);
            this.container.appendChild(btn);
            this.stars.push(btn);
        }
    }
    bind() {
        this.container.addEventListener('mouseover', e => {
            const btn = e.target.closest('button');
            if (btn) this.paint(+btn.dataset.value);
        });
        this.container.addEventListener('mouseout', () => this.paint(this.value));
        this.container.addEventListener('click', e => {
            const btn = e.target.closest('button');
            if (btn) this.value = +btn.dataset.value;
        });
    }
    paint(v) {
        this.stars.forEach((btn, i) => {
            btn.style.color = (this.max - i) <= v ? '#ffd700' : '#ccc';
        });
    }
}
new StarRating(document.getElementById('rating'));
copyright © 萬盛學電腦網 all rights reserved