less循环操作

  • less循环与js的while语句横向式,其实就是一个递归函数配合when函数一起使用,当满足条件将会停下来
.loop(@counter) when (@counter > 0) {
    width: (10px * @counter); // 一些属性的设置
    .loop(@counter - 1)
  }
  
div {
    .loop(5); // launch the loop
}
  • 说道了循环,怎么能少了数组和对象的遍历呢?list是less中用过来存放多个数据的一种数据类型等价于js的数组,每个数据之间使用空格或者是逗号间隔
  • 语法
@list1: 1px solid #ccc; // 这是一个空格间隔的数组
@list2: 1, 2, 3, 4;//这是一个逗号间隔的数组
// 两者在使用less 提供的 list 函数时没有区别
// 但是直接将两者赋值给属性值式 两者都会以字符串的形式赋值 导致逗号隔开的数组会保留逗号
.box {
    border: @list1;
    margin: @list2;
}

/*编译后*/
.box {
    border: 1px solid #ccc;
    margin: 1, 2, 3, 4; // 编译后逗号依然保留
}
  • length(@list)返回数组的长度
@list: 1px, solid, #ddd;

.box {
    z-index: length(@list);
}

/*编译后*/

.box {
    z-index: 3;
}
  • extract(@list,@index): 返回数值对应下标项@index的值(less list下标从一开始计算的)
@arr : 2,
3,
6,
8;

.box {
    z-index: extract(@arr, 3);
}

/*编译后*/
.box {
    z-index: 6;
}
  • 使用loop实现数组的变量
@list:100px,200px,300px;
.loop(@index) when(@index <= length(@list)){
	.box@{index}{
		width:extract(@list, @index);
	}
	.loop(@index + 1);
}
  • 使用range(@star,@end,@step)根据参数生成指定范围的数组;
@list: range(5) // 等价于 range(1,5,1) => @list: 1 2 3 4 5;
@list: range(5,8) // 等价于 range(5,8,1) => @list: 5 6 7 8;
@list: range(5px,15px,5) // start与end可以包含单位  @list: 5px 10px 15px;
  • 使用each(@list, 规则集): 遍历当前数组或者maps,在each参数而规则集中可以通过访问变量@index
    (当前遍历项的下标) @value(当前遍历项的值) @key(在maps中使用当前遍历项的key值)
// 遍历数组
.img {
    @pixel-ratio-list: 2, 3, 5;
    each(@pixel-ratio-list,{
            .pic-@{index} {
                z-index: @value;
            }
     })
}
/*编译后*/
.img {
   .pic-1 {
       z-index: 2;
   }
   .pic-2 {
       z-index: 3;
   }
   .pic-3 {
       z-index: 5;
   }
}

// 遍历maps
@obj : {
    size: 18;
    type: 19;
    desc: 20;
}

each(@obj, {
  .map-@{key} {
      z-index: @index;
      top: @value;
  }  
})

/*编译后*/
.map-size {
  z-index: 1;
  top: 18;
}
.map-type {
  z-index: 2;
  top: 19;
}
.map-desc {
  z-index: 3;
  top: 20;
} 
  • 还可以自定义each方法中的参数二规则集的@index@value@key三个变量名
@obj : {
    size: 18;
    type: 19;
    desc: 20;
}

each(@obj,.(@v, @k, @i){
  .map-@{k} {
      z-index: @i;
      top: @v;
  }  
})
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值