You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Livewire+Tailwind CSS+Alpine Js的星级评分hover效果问题咨询

星级评分组件hover联动效果实现方案

最简方案基于项目已引入的Alpine JS实现,无需修改原有Livewire业务逻辑,仅需添加少量前端属性即可:

改动步骤

  • 给最外层容器添加Alpine状态存储当前悬浮的星级值
  • 给每颗星星添加鼠标进出事件修改悬浮状态
  • 给星星添加动态类,当星星序号小于等于悬浮星级时显示黄色

修改后完整代码

<div class="flex items-center" x-data="{ hoverRating: 0 }">
    @for ($i = 0; $i < $this->rating; $i++)
    <svg wire:click.prevent="rate({{ $i+1 }})"
        @mouseenter="hoverRating = {{ $i+1 }}"
        @mouseleave="hoverRating = 0"
        class="cursor-pointer w-6 text-yellow-300 transition duration-150 @if(round($user->average_rating) > $i) text-yellow-300 @endif"
        :class="hoverRating >= {{ $i+1 }} ? 'text-yellow-300' : ''"
        xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
        fill="currentColor">
        <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
    </svg>
    @endfor
    @for ($i = $this->rating; $i < 5; $i++)
    <svg wire:click.prevent="rate({{ $i+1 }})"
        @mouseenter="hoverRating = {{ $i+1 }}"
        @mouseleave="hoverRating = 0"
        class="cursor-pointer w-6 transition duration-150 @if(round($user->average_rating) > $i) text-yellow-300 @endif"
        :class="hoverRating >= {{ $i+1 }} ? 'text-yellow-300' : 'hover:text-yellow-300'"
        xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"
        fill="currentColor">
        <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
    </svg>
    @endfor
    <span class="px-1 @if ($user->average_rating <= 2) bg-orange-500 @elseif($user->average_rating <= 4) bg-yellow-500 @else bg-green-500 @endif  text-white rounded">{{ $user->average_rating }}</span>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 13:36:01