css 自定义动态排列

需求就是显示一批头像,正常排列,很简单吧!

用弹性盒子再加上允许换行,就解决了吗?问题是:头像之间有间隔,就需要加margin-right,问题来了本行最后一个盒子的空隙大了,正好能放下一个头像,这时肯定去掉margin.(这里设定最后一个盒子空隙大,当然也可能正好或者多一点点)。

头像容器宽度不确定,头像个数不确定,就需要计算了

  nthChild(nodeList, selector) {
      var ret = [],
        reg = /(-?\d*)[n]*([+-]\d+)*/,
        m = selector.match(reg);
      if (selector === m[1]) {
        // nth-child:(2) - 纯数字,直接返回
        return [nodeList[parseInt(m[1]) - 1]];
      }
      var filter = function (i) {
        ++i; //nth从1开始, elem从0开始,elem的index要+1
        if (m[2]) {
          // 类似:nth-child:(-2n-1) / nth-child(n+2)
          if ("" === m[1]) {
            // nth-child(n+2)
            m[1] = 1;
          } else if ("-" === m[1]) {
            // nth-child(-n+2)
            m[1] = -1;
          } // else nth-child(-2n-1) / nth-child(2n+10)
        } else {
          // nth-child:(2n)
          m[2] = 0;
        }
        var n = (i - parseInt(m[2])) / parseInt(m[1]);
        // 正整数返回true
        return n === parseInt(n) && n >= 0 ? true : false;
      };
      function each(obj, fn) {
        var i = 0,
          len = obj.length,
          val;
        for (; i < len; i++) {
          val = fn.call(obj[i], i, obj[i]);
          if (val === false) break;
        }
      }
      each(nodeList, function (i) {
        //each 方法需要单独写
        if (filter(i)) {
          ret.push(this);
        }
      });
      return ret;
    }



let width = this.$refs.stus.offsetWidth % 100;   //剩余宽度(最后一个盒子空隙) = 头像容器宽度 % 头像宽度(包含margin)

let num = width >= 60 ? parseInt(stus / 100) + 1 : parseInt(stus / 100); //一行显示头像的数量 = 如果剩余宽度大于等于60(头像宽度,不包括maigin)就是容器宽度除以头像宽度+1;
//如果剩余宽度小于60,则
容器宽度除以头像宽度;
let stu_item = this.$refs.stu_item;   //所有头像的dom集合

var list = this.nthChild(stu_item, num + "n"); //计算出一行中最后一个dom
list.forEach((item) => {
item.style.marginRight
= "0";
});

 

posted @ 2023-07-12 15:23  波仔、  阅读(21)  评论(0编辑  收藏  举报