4

我知道 LESS 没有 if/else 结构,而是依赖于受保护的 mixin 语句。不过,它似乎无法在 mixin 中设置 LESS CSS 变量。

任何人都知道我如何实现某些效果。

if( ispercentage( @height ) {
  @height: "1024px";
}

// Calculations dependent on @height
@textAreaHeight = 0.5 * @height;
@buttonHeight = 0.2 * @height;

我查看了其他几个 stackoverflow 问题,包括: LESS CSS - 在 mixin 中设置变量

4

2 回答 2

2

Yes, it can be done. There was one bug that needed to be worked around.

Example LESS Code

//Set up guarded mixins
.setHeight(@h) when (ispercentage(@h)) { 
   @height: 1024px;
}

.setHeight(@h) when not (ispercentage(@h)) { 
   @height: @h;
}

//set up main height
@mainHeight: 50%;
body { height: @mainHeight;}

//call it by itself to make global
//.setHeight(@mainHeight); <-this failed (appears to be a bug)
.setHeight(50%); // <-this worked

.subsection { height: @height; /* just to show it is setting it */}

//use it for other globals
@textAreaHeight: 0.5 * @height;
@buttonHeight: 0.2 * @height;

textarea { height: @textAreaHeight}
button { height: @buttonHeight}

//override it locally
body.fixedHeight {
    .setHeight(300px);
    @textAreaHeight: 0.333 * @height;
    height: @height;
    textarea { height: @textAreaHeight}
}

Example CSS Output

body {
  height: 50%;
}
.subsection {
  height: 1024px; /* just to show it is setting it */
}
textarea {
  height: 512px;
}
button {
  height: 204.8px;
}
body.fixedHeight {
  height: 300px;
}
body.fixedHeight textarea {
  height: 99.9px;
}
于 2012-07-25T10:13:16.630 回答
1

您可以创建一个由类型“保护”的mixin,例如

.doHeightSet(@height) when ispercentage(@height) {
   .doheightSet(1024px)
}

.doHeightSet(@height) when not ispercentage(@height) {
   // Calculations dependent on @height
   @textAreaHeight: 0.5 * @height;
   @buttonHeight: 0.2 * @height;

   /* use variables here */
}

抱歉,我没有时间尝试这个,所以我可能犯了语法错误。

编辑更正的语法。

于 2012-07-10T11:48:54.613 回答