简体   繁体   中英

LESS mixin returning a custom variable name

I'm wondering if it's possible to create a mixin that can return a custom variable name.

For example, I have this mixin to return an rgba value.

.fadeColor(@color: #000; @opacity: 1) {
  @returnColor: rgba(red(@color), green(@color), blue(@color), @opacity);
}

I can then do something simple like:

.class {
  .fadeColor(#f00, .5);
  color: @returnColor;
}

I will get my faded red text.

Ideally what I'd like to have the mixin do is take in a name that will be the return value so I can do something like:

.class {
  .fadeColor(@myColor, #f00, .5);
  color: @myColor;
  .fadeColor(@myBG, #00f, .7);
  background-color: @myBG;
}

Is this possible? Is there a different approach that I can take to get the same result?

I know that fade would be the most workable solution in this specific example, but in general, is creating a variable from a variable a thing that can be done in LESS.

You can store the variable name in a variable and call it with two @@variable . You would have to store the name of the inner variable somewhere, though. You could try something like this:

.fadeColor(@name; @color: #000; @opacity: 1) {
  @return: rgba(red(@color), green(@color), blue(@color), @opacity);
}

.class1 {
    @name: return;
    .fadeColor(@name; blue; 1);
    border-color: @@name;
}

.class2 {
    @myColor: return;
    @myBG: return;
    &{
      .fadeColor(@myColor, #f00, .5);
      color: @@myColor;
    }
    &{
      .fadeColor(@myBG, #00f, .7);
      background: @@myBG;
    }
}

which will produce:

.class1 {
  border-color: #0000ff;
}
.class2 {
  color: rgba(255, 0, 0, 0.5);
  background: rgba(0, 51, 255, 0.7);
}

Probably that introduces a lot of unnecessary code. I don't know what you are trying to do, but you can probably find better ways to achieve what you want without requiring a mixin to return a value. You could, for example, send the property as a parameter:

.fadeColor(@property; @color: #000; @opacity: 1) {
    @{property}: rgba(red(@color), green(@color), blue(@color), @opacity);
}

.class2 {
    .fadeColor(color, #f00, .5);
    .fadeColor(background, #00f, .7);
}

In Less 1.7.0 you can store complete rulesets in variables (see: detached rulesets feature ). You might want to experiment with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM