js 实现星级评分

   最近的项目中有一个星级评分的需求,  自己就写了一下, 由于可能一个页面要用到多个,就采用了面向对象的写法。

  用到的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));
})

 

posted @ 2019-02-22 09:33  ken丶123  阅读(1528)  评论(0编辑  收藏  举报