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));
})

 

转载于:https://www.cnblogs.com/wjyz/p/10416476.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值