You need to enable JavaScript to run this app. jQuery半星星级评分:如何实现鼠标悬停预览与重复点击取消评分功能
优惠活动
大模型
产品
解决方案
定价
更多

jQuery半星星级评分:如何实现鼠标悬停预览与重复点击取消评分功能

半星jQuery评分组件功能扩展实现

核心实现逻辑

  • 悬停跟随预览:单独新增独立高亮类承载预览效果,和已选中的星级状态完全分离。鼠标在星级组内移动时,同步高亮当前悬停位置对应的半星区间;鼠标移出整个星级区域时,清除所有预览效果,还原用户已选定的星级状态。
  • 重复点击取消:记录上次选中的半星位置索引,当用户点击的位置和上次选中位置完全一致时,清除所有已选中的高亮状态,实现评分清零取消;否则执行原有正常选中逻辑。

调整后的完整代码

CSS部分

在原有样式基础上新增预览高亮类,和原有选中类的视觉效果保持一致:

.starR1{
    background: url('ico_review.png') no-repeat -52px 0;
    background-size: auto 100%;
    width: 15px;
    height: 30px;
    float:left;
    text-indent: -9999px;
    cursor: pointer;
}
.starR2{
    background: url('ico_review.png') no-repeat right 0;
    background-size: auto 100%;
    width: 15px;
    height: 30px;
    float:left;
    text-indent: -9999px;
    cursor: pointer;
}
/* 原有选中态样式 */
.starR1.on{background-position:0 0;}
.starR2.on{background-position:-15px 0;}
/* 新增悬停预览态样式 */
.starR1.hover-on{background-position:0 0;}
.starR2.hover-on{background-position:-15px 0;}

注:原CSS中的背景图地址按项目实际路径替换即可,无需引用外部资源

HTML部分

在原有半星span外层增加starRev类容器,包裹所有评分元素:

<div class="starRev">
  <span class="starR1 on">star1_left</span>
  <span class="starR2">star1_right</span>
  <span class="starR1">star2_left</span>
  <span class="starR2">star2_right</span>
  <span class="starR1">star3_left</span>
  <span class="starR2">star3_right</span>
  <span class="starR1">star4_left</span>
  <span class="starR2">star4_right</span>
  <span class="starR1">star5_left</span>
  <span class="starR2">star5_right</span>
</div>

JS部分

替换原有点击逻辑,新增悬停监听和取消选中逻辑:

const $starGroup = $('.starRev');
// 初始化匹配页面现有已选状态:获取最后一个带选中类的半星索引
let currentSelectedIndex = $starGroup.children('span.on').last().index();
// 无已选元素时index()返回-1,和默认未选中逻辑一致

// 悬停预览逻辑
$starGroup.on('mouseenter', 'span', function() {
  // 清除所有旧的预览高亮
  $starGroup.children('span').removeClass('hover-on');
  // 给当前悬停的元素及之前所有同级元素加预览高亮
  $(this).addClass('hover-on').prevAll('span').addClass('hover-on');
}).on('mouseleave', function() {
  // 鼠标移出整个星级区域时,清除预览效果,还原已选状态
  $(this).children('span').removeClass('hover-on');
});

// 点击选中/取消逻辑
$starGroup.on('click', 'span', function() {
  const clickIndex = $(this).index();
  // 判断是否点击当前已选中的相同评分
  if (clickIndex === currentSelectedIndex) {
    // 重复点击,清除所有选中高亮实现取消
    $starGroup.children('span').removeClass('on');
    currentSelectedIndex = -1;
  } else {
    // 正常选中逻辑
    $starGroup.children('span').removeClass('on');
    $(this).addClass('on').prevAll('span').addClass('on');
    currentSelectedIndex = clickIndex;
  }
  return false;
});

实际效果说明

  • 鼠标在星级区间移动时,会实时高亮对应到鼠标位置的半星档位,实现跟随预览效果,和实际选中的视觉效果完全一致
  • 选中任意档位后,再次点击同一个档位,会清除所有星级高亮,完成评分取消
  • 鼠标移出星级区域后,预览效果自动消失,保留用户最终选定的星级状态

内容的提问来源于stack exchange,提问作者StarFish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.05 17:54:04