用less制作方便的媒体查询函数

2,924 阅读1分钟

代码:

因为对less不熟悉,这个函数搞了一两个小时,该函数的特点是后面可以选择性的添加针对性的屏幕,我尝试放在前面,貌似不支持不定参数放在前面,如果道友有更方便的方式,请赐教!

.choose(@type, @style) when (@type=xs) {
  @media screen and (max-width: 767.999999px) {
    @style();
  }
}

.choose(@type, @style) when (@type=sm) {
  @media screen and (min-width: 768px) and (max-width: 991.99999px) {
    @style();
  }
}

.choose(@type, @style) when (@type=md) {
  @media screen and (min-width: 992px) and (max-width: 1199.99999px) {
    @style();
  }
}

.choose(@type, @style) when (@type=lg) {
  @media (min-width: 1200px) {
    @style();
  }
}

.loop(@i,@style,@list) when (@i<length(@list)) {
  .choose(extract(@list,@i+1), @style);
  .loop(@i+1, @style, @list);
}

.media(@style,...) {
  .loop(0, @style, @arguments);
}

用法:

.title {
  .media({
    color: red;
  }, xs, sm);
}

编译后:

@media screen and (max-width: 767.999999px) {
  .title {
    color: red;
  }
}
@media screen and (min-width: 768px) and (max-width: 991.99999px) {
  .title {
    color: red;
  }
}