较少的变量范围/上下文 [英] Less variables scopes/contexts

查看:87
本文介绍了较少的变量范围/上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的更少代码是这样的:

My less code is something like this:

body {
  @var: white;

  &.blue { @var: blue; }
  &.red { @var: red; }
  &.abc { @var: #badass; }

  background-color: @var;
}

我希望是,如果 body 具有类 .abc ,则变量 @var 的值将是 #badass(如果您具有类 .blue ),则值为 blue ,依此类推.但这不是发生的情况,变量的值不会随其剩余类而改变.

What I hope is, if the body has the class .abc the value of the variable @var is #badass, if you have the class .blue The value is blue and so on. But that's not what happens, the value of the variable dont change independent of their remains classes.

推荐答案

您需要为此创建参数混合:

You need to create a parametric mixin for that:

.bg(@color){
  background-color:@color;
}

,然后以下代码将起作用:

and then the following code will work:

body {
  .bg("white");

  &.blue{ .bg("blue");  }
  &.red { .bg("red");   }
  &.abc { .bg(#bada55); }

}

您正在做的事情不起作用,因为您正在重新分配变量 - 效果很好,但没有将新值写入类.(如果您只是在重新分配变量时,LESS创建新规则,那绝对没有任何意义.)而且,像任何其他编程语言一样,LESS具有作用域,因此在达到 background-color时:@var; @var 分配了值 white 并相应地创建规则.以下步骤将起作用(但毫无意义):

What you are doing isn't working, because you are reassigning the variable - which works perfectly, but not writing the new value to the class. (It would make absolutely no sense if LESS created new rules, every time you are just reassigning a variable.) Also, like any other programming language, LESS has scope, thus at the time it reaches background-color: @var; @var has the value white assigned to it and creates the rule accordingly. This following will work (but makes no sense of course):

body {
  @var: white;

  &.blue{ @var: blue;    background-color: @var;}
  &.red { @var: red;     background-color: @var;}
  &.abc { @var: #bada55; background-color: @var;}
  background-color: @var;
}

这篇关于较少的变量范围/上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆