在JavaScript中创建一个响应式星级评分可以通过以下步骤实现:
<div>
元素来实现。例如:<div id="star-rating"></div>
const starRatingContainer = document.getElementById('star-rating');
let currentRating = 0;
<span>
元素来表示每个星星。例如:function createStarRating(rating) {
let stars = '';
for (let i = 1; i <= 5; i++) {
if (i <= rating) {
stars += '<span class="star filled"></span>';
} else {
stars += '<span class="star"></span>';
}
}
return stars;
}
starRatingContainer.innerHTML = createStarRating(currentRating);
starRatingContainer.addEventListener('click', function(event) {
const starElements = starRatingContainer.querySelectorAll('.star');
const starIndex = Array.from(starElements).indexOf(event.target);
if (starIndex !== -1) {
currentRating = starIndex + 1;
starRatingContainer.innerHTML = createStarRating(currentRating);
}
});
.star {
display: inline-block;
width: 20px;
height: 20px;
background-color: gray;
margin-right: 5px;
}
.star.filled {
background-color: yellow;
}
这样,你就成功地在JavaScript中创建了一个响应式星级评分。用户可以通过点击星星来选择评分,评分的变化也会实时地反映在界面上。
领取专属 10元无门槛券
手把手带您无忧上云