<!DOCTYPE html>
<html leng="zh-CN">
<head>
<meta charset="UTF-8"/>
<title>星级评分--第二种方式</title>
<style>
body,ul,li{
padding: 0;
margin: 0;
}
li{
list-style-type: none;
}
.rating{
width:150px;
height: 27px;
margin:100px auto;
}
.rating-item{
float:left;
width:30px;
height: 27px;
background:url(img/start1.PNG) no-repeat;
cursor:pointer;
}
</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>
<ul class="rating" id="rating2">
<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="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script>
//闭包
var rating= (function() {
//点亮
var lightOn = function ($item, num) {
$item.each(function (index) {
if (index < num) {
$(this).css('background-position', '0 -45px');
} else {
$(this).css('background-position', '0 -15px');
}
})
};
var init = function (el, num) {
//缓存父容器
var $rating = $(el)
//缓存变量
$item = $rating.find('.rating-item')
//初始化
lightOn($item, num)
//事件(委托)绑定(子元素委托给父元素处理 rating-item 给$rating头两个是事件委托,最后一个是绑定,由于名字相同,就都用.表示了)
$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);
//this相当于el;
})
}
})
return {
//返回一个对象(对象是一个方法)
init:init
}
})();
rating.init("#rating",2);
rating.init("#rating2",3);
//$("#rating2").rating(4);
</script>
</body>
</html>