javascript - 为 :checked 之前的所有元素设置样式

标签 javascript jquery html

我正在为我的网站创建自己的星级评级系统。用户可以选择 1-5 颗星之间的任意值。

这个想法是,用户必须单击一颗星星来选择评级,并且单击的星星上留下的所有星星都会突出显示,包括单击的星星。

在幕后,我为每颗星星都有一个单选按钮。当用户单击星星时,单选按钮就会被选中。

但是,我希望在 mouseenter 上突出显示星星,如果用户没有单击,则在 mouseout 上星星应重置为由单选按钮。

Fiddly fiddle

我不确定如何最好地实现这一点,并且我当前的代码也给出了超出最大调用堆栈大小错误。不知道为什么。我找不到任何无限循环。

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/

相关文章:

javascript - jQuery show() 在 hide() 之后不起作用

Javascript,从 iFrame 访问框架集中的嵌套框架

python - 在 Python 中将 HTML 子标签更改为同级标签

javascript - Google map 和 100% 高度有问题吗?

javascript - select2 ajax 不工作

javascript - 单击时链接文本会更改。多看,少看 jquery - Bootstrap Accordion

javascript - 在自定义 JQuery 验证规则中读取非元素值的正确方法是什么?

javascript - ComponentDidMount 等不会按顺序触发函数

javascript - 取消选择数据表隐藏复选框

javascript - 请搜索 TreeView 帮助