星级评分实现
效果图:
图片:
完整代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>星级评分</title> <style> *{ padding:0; margin: 0; } .rating{ width:140px; height: 26px; margin:100px auto; } .rating-item{ float:left; width:28px; height: 26px; background:url(img/star.png) no-repeat ; cursor:pointer; list-style: none; } </style> </head> <body> <ul class="rating" id="rating"> <li class="rating-item" title="很不好"></li> <li class="rating-item" title="不好"></li> <li class="rating-item" title="一般"></li> <li class="rating-item" title="好"></li> <li class="rating-item" title="很好"></li> </ul> <script src="js/jquery.min.js" ></script> <script> let num=0; let $rating=$('#rating'); let $item=$rating.find('.rating-item'); let lightOn=function(num){ $item.each(function(index){ if(index<num){ $(this).css('background-position','0 -26px'); } else{ $(this).css('background-position','0 0'); } }) } //初始化 lightOn(num); //事件绑定 $rating.on('mouseover','.rating-item',function(){ //事件委托 lightOn($(this).index()+1); }).on('click','.rating-item',function(){ num=$(this).index()+1; let info=$(this).attr("title"); console.log(`您选择了“${info}”`); }).on('mouseout',function(){ lightOn(num); }) </script> </body> </html>