先上下自己的脚本文件:
1 $.fn.DyStar = function (option, callback) { 2 var defaults = { 3 count: 5, 4 url: 'images/star.gif' 5 }; 6 var opt = $.extend(defaults, option), 7 obj = $(this); 8 obj.css({ 9 16 * opt.count, 10 height: 16 11 }); 12 for (i = 0; i < opt.count; i++) { 13 $("<span></span>").css({ 14 16, 15 height: 16, 16 float: "left", 17 "background-image": "url(" + opt.url + ")" 18 }).appendTo($(this)); 19 } 20 21 22 obj.each(function () { 23 if($(this).attr("data-value")){ 24 $(this).children().not($(this).children("span:lt(" + $(this).attr("data-value") + ")").css("background-position", "0px 32px")).css("background-position", "0px 0px"); 25 $(this).data("starcount",$(this).attr("data-value")-1); 26 } 27 }); 28 29 30 31 obj.filter("[data-readonly!='true']").on({ //只读的 不添加这些事件 32 click: function () { 33 obj = $(this).parent(); 34 var starindex = $(this).index() + 1; 35 obj.children().not($(this).prevAll().add($(this)).css("background-position", "0px 32px")).css("background-position", "0px 0px"); 36 obj.data("starcount", $(this).index()); 37 if (typeof option == 'function') { 38 option(starindex); 39 } 40 if (typeof callback == 'function') { 41 callback(starindex); 42 } 43 }, 44 mouseover: function () { 45 obj = $(this).parent(); 46 obj.children().not($(this).prevAll().add($(this)).css("background-position", "0px 16px")).css("background-position", "0px 0px"); 47 }, 48 mouseout: function () { 49 obj = $(this).parent(); 50 obj.children().not(obj.children("span:lt(" + (obj.data("starcount") + 1) + ")").css("background-position", "0px 32px")).css("background-position", "0px 0px"); 51 } 52 }, "span"); 53 }
用法:
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>豆芽评星</title> 6 <script src="jquery-1.8.3.min.js"></script> 7 <script src="DyStar.js"></script> 8 <style> 9 body { 10 font-size:12px; 11 font-weight:bold; 12 } 13 </style> 14 <script> 15 $(function () { 16 $(".star").DyStar(function (data) { 17 alert(data); 18 }); 19 $(".star3").DyStar({ count: 4}, function (data) { 20 alert(data); 21 }); 22 }); 23 </script> 24 </head> 25 <body> 26 <div class="star"></div> 27 <div class="star" data-value="1"></div> 28 <div class="star"></div> 29 <br /> <br /> <br /> 30 下面的 都默认复制为2颗星 31 <div class="star3"></div> 32 <div class="star3" data-value="2"></div> 33 下面这个是只读的 其余的可以重选 34 <div class="star3" data-readonly="true" data-value="3"></div> 35 36 </body> 37 </html>
效果: