• 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));
    })
  • 相关阅读:
    类的使用(基础)
    <cf>Two Problems
    <cf>Walking in the Rain
    一些程序的整理
    <codeforces>Little Elephant and Sorting
    HDU 1172 猜数字(枚举)
    HDUOJ 1879 继续畅通工程
    error C2679: binary '<<' : no operator defined which takes a righthand operand of type 'class std::basic_s
    HDUOJ 1198 Farm Irrigation(并查集)
    HDU 1222 Wolf and Rabbit
  • 原文地址:https://www.cnblogs.com/wjyz/p/10416476.html
Copyright © 2020-2023  润新知