最近的項目中有一個星級評分的需求, 自己就寫了一下, 由於可能一個頁面要用到多個,就采用了面向對象的寫法。
用到的png圖片也放到這里。
js要用到jquery。
css:
.sr-star{ display: flex; margin-bottom:50px; } .sr-star-item{ width:18px; height:18px; background:url("./img/empty.png") no-repeat; background-size:18px 18px; margin-right:8px; cursor: pointer; } .str-star-item.active{ background-image: url("./img/full.png"); }
js:
$(function () { function SrScore(el) { this.$el = $(el); this.init(); this.$items = this.$el.find('.sr-star-item'); } SrScore.prototype.init = function () { var str = ''; for (var i = 0 ;i < 5; i++) { str += '<div class="sr-star-item"></div>' } this.$el.append(str); this.$bindEvent(); }; SrScore.prototype.$bindEvent = function () { var that = this; this.$el.on('click', '.sr-star-item', function () { that.onScore($(this).index()); }) }; SrScore.prototype.onScore = function (n) { this.$items.each(function (index) { var $this = $(this); if (index <= n) { $this.addClass('active'); } else { $this.removeClass('active'); } }) };
window.SrStore = SrScore; })
由於我這里的需求只有點擊哪個,就點亮那些。 所以事件里面就只寫了一個click, 如果有鼠標移入到哪個上就點亮的需求, 可以加上mouseover和mouseout事件,在構造函數中加一個屬性index:this.index = 0, mouseover的時候,
that.onScore($(this).index()), click的時候, 將this.index = $(this).index(), mouseout的時候,that.onScore(that.index);
調用:
new SrScore(el);
如果頁面中多個同樣類名的都要加這個, 可以先遍歷類名,然后將每個this放入其中
$('.sr-star').each(function () { new SrScore($(this)); })