HTML5商城开发三 jquery 星星评分插件
展示:
实现方法:
1.html引用star-grade.js
<script type="text/javascript" src="Scripts/star-grade.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".sstar").BindStars();//使用属性data-score获取评分值
$("#pye").SetStars(3);//传分数,自动列出星星
});
</script>
<body>
<div class="starscore sstar">
<i></i>
<i></i>
<i></i>
<i></i>
<i></i>
</div>
<span id="ye"></span>
<div class="starscore" id="pye"></div>
<div class="starscore starscore_sm" >
<i class="inred"></i>
<i class="inred"></i>
<i></i>
<i></i>
<i></i>
</div>
<div class="starscore starscore_lg">
<i class="onred"></i>
<i class="onred"></i>
<i></i>
<i></i>
<i></i>
</div>
</body>
2.css样式
@charset "utf-8";
/* CSS Document */
.starscore {
width: 200px;
height: 30px;
}
.starscore i {
width: 14px;
height: 14px;
background: url(images/gray.gif) no-repeat; /* 14x14的灰色星星图标 */
display: inline-block;
vertical-align: middle;
background-size: contain;
}
.starscore i.inred, .starscore i.onred {
background: url(images/yel.gif) no-repeat; /* 14x14的黄色星星图标 */
}
.starscore_lg > i {
width: 18px;
height: 18px;
}
.starscore_sm > i {
width: 12px;
height: 12px;
}
3.插件js源码
/*
* jq扩展--星星评分插件
*
* 通过对象的属性data-score获取评分值
* 星星使用元素i表示,绑定星星背景图
* 鼠标进入、离开事件的绑定样式为inred,改变背景图
* 点击事件的绑定样式为onred,改变背景图
*/
(function ($) {
"use strict";
$.fn.BindStars = function () {
var starElement = $(this);
starElement.children("i").mouseleave(function () {
starElement.find("i").each(function (index) {
$(this).removeClass("inred");
});
});
starElement.children("i").mouseenter(function () {
var curIndex = starElement.find("i").index(this);
starElement.find("i").each(function (index) {
if (index <= curIndex) {
$(this).addClass("inred");
}
else {
$(this).removeClass("inred");
}
});
});
starElement.children("i").click(function () {
var curIndex = starElement.find("i").index(this);
starElement.find("i").each(function (index) {
if (index <= curIndex) {
$(this).addClass("onred");
}
else {
$(this).removeClass("onred");
}
});
starElement.attr("data-score", curIndex + 1);
});
};
$.fn.SetStars = function (score) {
var scoreStr = "";
for (var i = 0; i < 5; i++) {
if (i < score) {
scoreStr += "<i class='onred'></i>";
} else {
scoreStr += "<i></i>";
}
}
$(this).html(scoreStr);
};
})(window.jQuery);

浙公网安备 33010602011771号