Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Less 循环遍历和踩坑 #25

Open
maomao1996 opened this issue Dec 16, 2021 · 0 comments
Open

Less 循环遍历和踩坑 #25

maomao1996 opened this issue Dec 16, 2021 · 0 comments
Labels
CSS css 相关

Comments

@maomao1996
Copy link
Owner

maomao1996 commented Dec 16, 2021

Less 循环遍历和踩坑

递归混合

Recursive Mixins 文档

.color {
  // 定义遍历对象
  @colors: #111, #444, #999;

  // 定义循环最大值,通过 length 函数拿到遍历对象的长度
  @len: length(@colors);

  // 定义循环方法 当 index 大于 len 时结束循环
  .loop(@index) when(@index<=@len) {
    // 使用 extract 方法通过当前索引拿到对应的颜色值
    @current-color: extract(@colors, @index);
    // 使用 replace 方法移除颜色值中的 # 字符
    @selector: replace(@current-color, '#', '', 'gi');
    &-@{selector} {
      color: @current-color;
    }

    // 递归调用
    .loop(@index + 1);
  }

  // 开始循环
  .loop(1);
}

编译输出代码

.color-111 {
  color: #111;
}
.color-444 {
  color: #444;
}
.color-999 {
  color: #999;
}

递归混合 — Playground

each 函数

Less 在 v3.7.0 版本中加入了 each 函数

.color {
  // 定义遍历对象
  @colors: #111, #444, #999;

  // 调用 each 函数
  each(@colors, {
    // 使用 replace 方法移除颜色值中的 # 字符
    @selector: replace(@value, "#", "", "gi");
    &-@{selector} {
      color: @value;
    }
  });
}

当使用了 each 函数后代码简化了很多,怪不得我不喜欢用 Less 一点都不适合偷懒,一个循环都要写一坨代码

each — Playground

嵌套 each

@margin-sizes: 10, 16;
@direction: {
  t: top;
  r: right;
  b: bottom;
  l: left;
};
each(@margin-sizes, {
  .m {
    &-@{value}{
      margin: 1px * @value;
    }
    // each 函数默认使用 @value,@key,@index 为变量名
    // 当通过 #() 或者 .() 的样式为开头传递变量名时
    // each 函数会获取传入的变量的名并按顺序将其绑定为 @value,@key,@index 的值
    each(@direction, .(@v, @k) {
      &@{k}-@{value} {
        margin-@{v}: 1px *  @value;
      }
    });
  }
});

编译输出代码

.m-10 {
  margin: 10px;
}
.mt-10 {
  margin-top: 10px;
}
.mr-10 {
  margin-right: 10px;
}
.mb-10 {
  margin-bottom: 10px;
}
.ml-10 {
  margin-left: 10px;
}
.m-16 {
  margin: 16px;
}
.mt-16 {
  margin-top: 16px;
}
.mr-16 {
  margin-right: 16px;
}
.mb-16 {
  margin-bottom: 16px;
}
.ml-16 {
  margin-left: 16px;
}

嵌套 each — Playground

注释踩坑点

: 在使用嵌套时,如果当前作用域下没有样式规则,并写了一个块级注释后会编译出一个空的样式类

.box {
  /* 这是测试用的块级注释 */
  &-item {
    /* 这是测试用的块级注释 */
    width: 100px;
  }
  &-empty {
    // 这是测试用的行内注释
  }
}

编译输出代码

.box {
  /* 这是测试用的块级注释 */
}
.box-item {
  /* 这是测试用的块级注释 */
  width: 100px;
}

原因: Less 编译后的代码会保留块级注释(可以用来添加版权信息等,Sass 也是如此)

注释踩坑 — Playground

相关资料

@maomao1996 maomao1996 added the CSS css 相关 label Dec 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CSS css 相关
Projects
None yet
Development

No branches or pull requests

1 participant