星级评分--封装成jquery插件
<!
DOCTYPE
html>
<
html
>
<
head
>
<
meta
charset="utf-8">
<
title
>星级评分--封装成jquery插件</
title
>
</
head
>
<
style
type="text/css">
body,ul,li{
margin: 0;
padding: 0;
}
li{
list-style-type: none;
}
.rating{
width: 162px;
height: 32px;
margin: 100px auto;
}
.rating-item{
float: left;
width: 32px;
height: 32px;
background: url('./img/rating.png') no-repeat;
cursor: pointer;
}
</
style
>
<
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
>
</
body
>
<
script
type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></
script
>
<
script
type="text/javascript">
//封装成jquery插件
var rating = (function(){
//点亮星星
var lightOn = function($item,num){
$item.each(function(index){
if(index <
num
){
$(this).css('background-position','0 -32px');
}else{
$(this).css('background-position','0 0');
}
});
};
//初始化
var init = function(el,num){
var $rating = $('#rating'),
$item = $rating.find('.rating-item');
//初始化,点亮num个星星
lightOn($item,num);
$rating.on('mouseover','.rating-item',function(){//鼠标移入时,触发相应操作
lightOn($item,$(this).index() + 1);
}).on('click','.rating-item',function(){//鼠标点击时,触发相应操作
num = $(this).index() + 1;
}).on('mouseout',function(){//鼠标移出是,触发相应的操作
lightOn($item,num);
});
};
//jquery插件
$.fn.extend({
rating : function(num){
return this.each(function(){
init(this,num);
});
}
});
return {
init : init
};
})();
$(".rating").rating(3);
</script>
素材:
![](https://images2018.cnblogs.com/blog/1195700/201804/1195700-20180411153309108-2027115918.png)