我使用 CSS HTML 和 Javascript 创建了一个星级评级应用程序。当我单击星星时,它不会按预期突出显示。假设我单击第三颗星,然后在它突出显示之前只单击两颗星。
我不明白我应该如何处理 css 属性,这将使当前单击的星号突出显示。
let stars = document.querySelectorAll('.star');
document.querySelector('.star-container').addEventListener('click', starRating);
let rating = document.querySelector('.rating');
function starRating(e) {
if (e.target.classList[0] == 'star') {
stars.forEach((star) => star.classList.remove('star__checked'));
for (i = stars.length - 1, j = 0; i >= 0; i--, j++) {
if (stars[i] !== e.target) {
stars[i].classList.add('star__checked');
} else {
stars[i].classList.add('star__checked');
rating.textContent = `${j + 1}/5`;
break;
}
}
} else {
stars.forEach((star) => star.classList.remove('star__checked'));
rating.textContent = `${0}/5`;
}
}Run Code Online (Sandbox Code Playgroud)
.star-container {
display: flex;
width: 350px; …Run Code Online (Sandbox Code Playgroud)