javascript - 如何使用 JQuery 实现星级评分
问题描述
大家好,我对如何使用简单的 jquery 检查单选按钮并在其旁边显示值表示怀疑
例如,当第一个输入标签被选中时,星号应将其更改为黄色 :) 未选中时,应将其更改回正常颜色
请不要向我推荐任何插件
.myratings {
font-size: 0.875rem;
color: green;
position: relative;
top: 12px;
margin-left: 9px;
}
.rating>[id^="star"] {
display: none
}
.rating>label:before {
margin-right: 5px;
font-size: 1.75rem;
display: inline-block;
content: "\2605";
font-family: "Font Awesome 5 Free";
}
.rating>.half:before {
content: "\2605";
position: absolute;
width: 10px;
overflow: hidden;
}
.rating>label {
color: #ddd!important;
float: right
}
.rating:not(:checked)>label:hover,
.rating:not(:checked)>label:hover~label {
color: #FFD700!important;
}
.checked {
color: #FFD700!important;
}
.rating>[id^="star"]:checked+label:hover,
.rating>[id^="star"]:checked~label:hover,
.rating>label:hover~[id^="star"]:checked~label,
.rating>[id^="star"]:checked~label:hover~label {
color: #FFD700!important;
}
<fieldset class="rating">
<input type="radio" id="star5" name="rating" value="5" /><label class="full" for="star5" title="Awesome"></label>
<input type="radio" id="star4" name="rating" value="4" /><label class="full" for="star4" title="Pretty good - 4 stars"></label>
<input type="radio" id="star3" name="rating" value="3" /><label class="full" for="star3" title="Meh - 3 stars"></label>
<input type="radio" id="star2" name="rating" value="2" /><label class="full" for="star2" title="Kinda bad - 2 stars"></label>
<input type="radio" id="star1" name="rating" value="1" /><label class="full" for="star1" title="poor - 1 star"></label>
</fieldset>
<span class="myratings">0</span>
解决方案
解决此问题的一种方法是使用 vanilla javascript 来跟踪当前选择的评级并使用适当的颜色更新每个标签。
我用来创建此解决方案的参考资料: setAttribute
//The current rating
let currentRating = 0;
//Grab all the label elements and sort them from least to greatest using the last number in the htmlFor string
let labels = Array.from(document.getElementsByTagName("label")).sort((a, b) => a.htmlFor.substring(4) - +b.htmlFor.substring(4));
//onclick event handler
function clicker(num) {
//If the user clicked on the current rating, set to 0
if (currentRating == num) currentRating = 0;
//Otherwise, set it to the current rating
else currentRating = num;
//Update the text for the current rating
document.querySelector(".myratings").innerHTML = currentRating;
//Loop through all the labels and update their colors
for (let i = 0; i <= 4; i++) {
let label=labels[i];
if ((i + 1)> currentRating) label.setAttribute('style', 'color:#ddd !important');
else label.setAttribute('style', 'color:#FFD700 !important')
}
推荐阅读
- node.js - 我需要抓取未在视图源中显示的内容:浏览器
- git - GitHub 推送失败 - 被拒绝 - 未能将参考推送到 github
- python - python 字符串变量将 '\b' 更改为 '\x08' 和 '\a' 更改为 '\x07' 并且对于某些数字和字符也是如此?为什么?
- bash - 找出shell脚本中存在哪些文件
- javascript - 如何将矩形移动到另一个旋转和平移矩形的左上角?
- html - 使用圆形图像作为边框图像
- python - django中的路径问题
- html - Webp 图像在本地显示,但在部署后不在远程显示
- php - PHP不匹配条件,但仍然在不匹配条件下执行一个类?
- python - 代码运行时播放器不显示?