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 = "☆"); }
onmouseover 觸發,根據索引將當前及之前星星填滿(★),之後置空(☆)。table.onmouseout 捕獲鼠標離開表格區域,全部重置為 ☆。ArrayIndexof 將 HTMLCollection 視為數組查找位置。onclick 記錄選中值,onmouseout 時恢復到已選狀態。className 切換樣式。table.onmouseover,用 e.target.closest('td') 判斷。<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、語義化、鍵盤可訪問、表單原生提交值。
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'));