今天晚上研究下 五星级评分效果,类似于淘宝后台评分效果,如下图所示:
思路: 当鼠标移到一颗星的时候 判断当前的索引 当前及当前的索引前面的星星亮起来 每当移到任何一颗星星时候 下面跟随提示 mouseout时候 提示消失,移出时 全部变灰。每当点击一颗星星时候 同样判断当前的索引 当前及当前之前的星星都亮起来,mouseout时候 点击时候的星星(亮) 同样保持亮的状态。
HTML代码如下:
css代码如下:
1
JS代码如下:
1 /** 2 * JS评分效果 3 */ 4 function Score(options) { 5 this.config = { 6 selector : '.star', // 评分容器 7 renderCallback : null, // 渲染页面后回调 8 callback : null // 点击评分回调 9 }; 10 11 this.cache = { 12 aMsg : [ 13 "很不满意|差得太离谱,与卖家描述的严重不符,非常不满", 14 "不满意|部分有破损,与卖家描述的不符,不满意", 15 "一般|质量一般,没有卖家描述的那么好", 16 "满意|质量不错,与卖家描述的基本一致,还是挺满意的", 17 "非常满意|质量非常好,与卖家描述的完全一致,非常满意" 18 ], 19 iStar : 0, 20 iScore : 0 21 }; 22 23 this.init(options); 24 } 25 26 Score.prototype = { 27 28 constructor: Score, 29 30 init: function(options){ 31 this.config = $.extend(this.config,options || {}); 32 var self = this, 33 _config = self.config, 34 _cache = self.cache; 35 36 self._renderHTML(); 37 }, 38 _renderHTML: function(){ 39 var self = this, 40 _config = self.config; 41 var html = '' + 42 ''; 43 $(_config.selector).each(function(index,item){ 44 $(item).append(html); 45 $(item).wrap($(' ')); 46 var parentCls = $(item).closest('.parentCls'); 47 self._bindEnv(parentCls); 48 }); 49 50 }, 51 _bindEnv: function(parentCls){ 52 var self = this, 53 _config = self.config, 54 _cache = self.cache; 55 56 $(_config.selector + ' li',parentCls).each(function(index,item){ 57 58 // 鼠标移上 59 $(item).mouseover(function(e){ 60 var offsetLeft = $('ul',parentCls)[0].offsetLeft; 61 ismax(index + 1); 62 63 $('p',parentCls).hasClass('hidden') && $('p',parentCls).removeClass('hidden'); 64 $('p',parentCls).css({'left':index*$(this).width() + 12 + 'px'}); 65 66 67 var html = '' + 68 ''+index+'分 '+_cache.aMsg[index].split('|')[0]+'' + 69 '' + _cache.aMsg[index].split('|')[1]; 70 $('p',parentCls).html(html); 71 }); 72 73 // 鼠标移出 74 $(item).mouseout(function(){ 75 ismax(); 76 !$('p',parentCls).hasClass('hidden') && $('p',parentCls).addClass('hidden'); 77 }); 78 79 // 鼠标点击 80 $(item).click(function(e){ 81 var index = $(_config.selector + ' li',parentCls).index($(this)); 82 _cache.iStar = index + 1; 83 84 !$('p',parentCls).hasClass('hidden') && $('p',parentCls).addClass('hidden'); 85 var html = '' + 86 index + 87 '分' +_cache.aMsg[index].split('|')[1]; 88 89 $('.desc',parentCls).html(html); 90 _config.callback && $.isFunction(_config.callback) && _config.callback(); 91 }); 92 93 }); 94 95 function ismax(iArg) { 96 _cache.iScore = iArg || _cache.iStar; 97 var lis = $(_config.selector + ' li',parentCls); 98 99 for(var i = 0; i < lis.length; i++) {100 lis[i].className = i < _cache.iScore ? "on" : "";101 }102 }103 }104 };105 106 $(function(){107 new Score({});108 });