五星好评的js代码
时间: 2023-09-03 13:12:51 浏览: 97
很高兴听到您想要五星评价的JavaScript代码!以下是一个简单的五星评级系统的示例代码:
HTML:
```html
<div class="rating">
<span class="star" data-rating="1"></span>
<span class="star" data-rating="2"></span>
<span class="star" data-rating="3"></span>
<span class="star" data-rating="4"></span>
<span class="star" data-rating="5"></span>
<input type="hidden" name="rating" class="rating-value" required>
</div>
```
CSS:
```css
.rating {
display: flex;
justify-content: center;
align-items: center;
margin: 20px 0;
}
.star {
font-size: 30px;
color: #ccc;
cursor: pointer;
transition: color 0.3s ease-in-out;
margin: 0 5px;
}
.star:hover,
.star.active {
color: #ffce00;
}
```
JavaScript:
```js
const stars = document.querySelectorAll('.star');
const ratingValue = document.querySelector('.rating-value');
let index;
for (let i = 0; i < stars.length; i++) {
stars[i].addEventListener('click', function() {
index = i;
ratingValue.value = index + 1;
for (let j = 0; j < stars.length; j++) {
if (j <= index) {
stars[j].classList.add('active');
} else {
stars[j].classList.remove('active');
}
}
});
}
```
这段代码创建了一个包含五个星形元素的评级系统。点击星形元素将为评级系统设置一个评分。单击星形元素时,将使用CSS类“ active”突出显示所选星形元素,并将所选索引值设置为表单输入字段的值。