我正在为我的网站创建自己的星级评级系统。用户可以选择 1-5 颗星之间的任意值。
这个想法是,用户必须单击一颗星星来选择评级,并且单击的星星上留下的所有星星都会突出显示,包括单击的星星。
在幕后,我为每颗星星都有一个单选按钮。当用户单击星星时,单选按钮就会被选中。
但是,我希望在 mouseenter
上突出显示星星,如果用户没有单击,则在 mouseout
上星星应重置为由单选按钮。
我不确定如何最好地实现这一点,并且我当前的代码也给出了超出最大调用堆栈大小
错误。不知道为什么。我找不到任何无限循环。
HTML
<div class="starrating-container">
<div class="star"><input type="radio" name="star-radio" value="1" hidden></div>
<div class="star"><input type="radio" name="star-radio" value="2" hidden></div>
<div class="star"><input type="radio" name="star-radio" value="3" hidden></div>
<div class="star"><input type="radio" name="star-radio" value="4" hidden></div>
<div class="star"><input type="radio" name="star-radio" value="5" hidden></div>
</div>
CSS
.starrating-container {
display: inline-block;
}
.star {
float: right;
display: inline-block;
width: 24px;
height: 24px;
background-image: url('http://www.timelinecoverbanner.com/cliparts/wp-content/digital-scrapbooking/lemon-star-md1.png');
background-size: cover;
-webkit-filter: saturate(0);
}
JS
$('.star').on({
'mouseenter': function() {
$(this).nextAll().andSelf().css('-webkit-filter', 'saturate(1)');
$(this).prevAll().css('-webkit-filter', 'saturate(0)');
},
'mouseleave': function() {
$(this).siblings().find(':radio').each(function() {
if($(this).val() > $('.star input[name=radioName]:checked').val()) {
$(this).nextAll().andSelf().css('-webkit-filter', 'saturate(1)');
$(this).prevAll().css('-webkit-filter', 'saturate(0)');
}
});
},
'click': function() {
$(this).children(':radio').click();
}
});
最佳答案
这是一个很好的解决方案: Accessible star rating widget with pure CSS
关于javascript - 为 :checked 之前的所有元素设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910134/