简体   繁体   English

如何在less.js中为DRY编写循环function或混合变量

[英]How to write a loop function or mixin with variables in less.js for DRY

Is there any efficient way to write this code with less.js :有没有什么有效的方法可以用less.js编写这段代码:

  • I've got already 3 variables colors: @vert, @violet and @orange我已经有 3 个变量 colors:@vert、@violet 和 @orange
li {
    &:nth-child(1) {
        background: @vert;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @vert;
            }
        }
    }
    &:nth-child(2) {
        background: @violet;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @violet;
            }
        }
    }
    &:nth-child(3) {
        background: @orange;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @orange;
            }
        }
    }
}    

I thought of a mixin , but I'm not writing well: Any help please?我想到了一个mixin ,但我写得不好:有什么帮助吗?

.colored-menu(@number, @color) {
    &:nth-child(@number) {
        background: @color;
        &:hover,
        &.open {
            >.dropdown-menu li {
                background: @color;
            }
        }
    }
}

and calling it like this:并这样称呼它:

.colored-menu(1,@vert);
.colored-menu(2,@violet);
.colored-menu(3,@orange);

You can use your approach with some edits:您可以使用您的方法进行一些编辑:

// mixin
.colored-menu(@number; @color) { // the docs recommends semi-colons instead of commas
  &:nth-child(@{number}) { // variable requires curly brackets for interpolation
    background: @color;
    &:hover,
    &.open {
      > .dropdown-menu li {
        background: @color;
      }
    }
  }
}

// ruleset
li {
  .colored-menu(1; @vert);
  .colored-menu(2; @violet);
  .colored-menu(3; @orange);
}

Also, consider using the each list function:另外,考虑使用each列表 function:

// list
@colors: @vert, @violet, @orange;

// ruleset
li {
  each(@colors, {
    &:nth-child(@{index}) {
      background: @value;
      &:hover,
      &.open {
        > .dropdown-menu li {
          background: @value;
        }
      }
    }
  });
}

The output from both approaches are the same (in this instance).两种方法的 output 是相同的(在这种情况下)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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