展示:
实现方法:
1.html引用star-grade.js
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 += ""; } else { scoreStr += ""; } } $(this).html(scoreStr); }; })(window.jQuery);