📅  最后修改于: 2023-12-03 14:58:00.680000             🧑  作者: Mango
在开发前端网页时,我们经常需要添加rating(评分)功能,这时我们可以使用复选框来实现评分的效果,同时我们还需要按照用户的选择顺序显示评分效果。本文将介绍如何使用JavaScript和React来实现这一功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rating</title>
<style>
input[type="checkbox"] {
display: none; /* 隐藏复选框 */
}
label {
font-size: 30px;
color: #ddd;
cursor: pointer;
}
label:before {
content: "\2605"; /* 设置 label 的文本为星号,Unicode编码:☆(2B50)或 ★(2605) */
}
input[type="checkbox"]:checked + label:before {
content: "\2605";
color: #ff0;
}
</style>
</head>
<body>
<div id="rating">
<input type="checkbox" id="star1" value="1">
<label for="star1"></label>
<input type="checkbox" id="star2" value="2">
<label for="star2"></label>
<input type="checkbox" id="star3" value="3">
<label for="star3"></label>
<input type="checkbox" id="star4" value="4">
<label for="star4"></label>
<input type="checkbox" id="star5" value="5">
<label for="star5"></label>
</div>
<script>
const stars = document.querySelectorAll('input[type="checkbox"]');
const rating = document.getElementById('rating');
stars.forEach(star => star.addEventListener('click', handleRating));
function handleRating(e) {
const starChecked = parseInt(e.target.value);
stars.forEach(star => {
const starValue = parseInt(star.value);
star.value = starChecked >= starValue ? starChecked : starValue - 1;
star.checked = starValue <= starChecked;
});
setRating();
}
function setRating() {
let ratingValue = 0;
stars.forEach(star => {
if (star.checked) {
ratingValue += parseInt(star.value);
}
});
rating.setAttribute('data-rating', ratingValue);
}
</script>
</body>
</html>
import { useState } from 'react';
function Rating() {
const [ratingValue, setRatingValue] = useState(0);
function handleRating(e) {
const starChecked = parseInt(e.target.value);
setRatingValue(stars => {
return stars.map(star => {
const starValue = parseInt(star.value);
star.value = starChecked >= starValue ? starChecked : starValue - 1;
star.checked = starValue <= starChecked;
return star;
});
});
}
return (
<div data-rating={ratingValue}>
<input type="checkbox" id="star1" value="1" onClick={handleRating} />
<label htmlFor="star1" />
<input type="checkbox" id="star2" value="2" onClick={handleRating} />
<label htmlFor="star2" />
<input type="checkbox" id="star3" value="3" onClick={handleRating} />
<label htmlFor="star3" />
<input type="checkbox" id="star4" value="4" onClick={handleRating} />
<label htmlFor="star4" />
<input type="checkbox" id="star5" value="5" onClick={handleRating} />
<label htmlFor="star5" />
</div>
);
}
本文介绍了使用 JavaScript 和 React 实现评分功能的方法,同时也是复选框的一个新的用法。通过本文,你可以学习到如何动态修改元素的属性和样式,以及如何在 React 中使用 useState 钩子函数实现状态管理。