四、项目中使用到的函数与循环总结

Less

# 函数参数带有类名设置

# 函数定义

这个根据每个的设计稿和基础适配的font-size决定,我这里只是说传入参数生成对应的rem的值

@base:750 / 720 * 0.01;
.px2rem(@name, @px) {
     @{name}: @px * @base * 1rem;
}
1
2
3
4

# 函数调用

.px2rem(margin-top,250);
1

# 使用语法

如果是参数,类名参数要加大括号@{name},不是冒号左边的不需要,如果有双引号也要加。

# less循环输出类名

# 目标输出

.a{
  background: url("./resource/a.png") top/100% no-repeat;
}
.b{
  background: url("./resource/b.png") top/100% no-repeat;
}
.c{
  background: url("./resource/c.png") top/100% no-repeat;
}

1
2
3
4
5
6
7
8
9
10

# 实现思路

  • 由于形式上面很类似,所以先定义一个模板函数;
  • 定义一个less列表,把需要的类名都写上;
  • 循环遍历列表,调用函数。

# 实现步骤

  1. 定义函数
    .backgroundcard(@className,@pngName){
          .@{className}{
                background: url("./resource/@{pngName}.png") top/100% no-repeat;
          }
    }
1
2
3
4
5
  1. 定义一个数组
@bgcardList:a,b,c,d,e,f,g;
1
  1. 循环遍历
.loop(@i) when (@i < length(@bgcardList)+1){
    .backgroundcard(extract(@bgcardList, @i),extract(@bgcardList, @i));
    .loop(@i+1);
}
.loop(1);
1
2
3
4
5

# 语法说明

  • 列表函数
    • 获取列表的长度 length(@bgcardList) // 7
    • 获取列表元素 extract(@bgcardList, 3) // c
  • 循环函数
    • loop定义循环次数,when条件判断,符合进入函数,不符合不进入函数。之后次数+1,形成循环。
    • loop函数调用,直接传值1

之后将不定期更新...

更新时间: 2021-09-15 12:03