从字符串定义LESS变量

时间:2014-01-20 23:01:31

标签: less mixins

我正在尝试编写一个mixin,它返回一个用于将px转换为em的变量。我玩过一些东西,但最终我想调用一个mixin并获得类似于SASS功能的返回值。基于这里的返回值:http://www.lesscss.org/#-return-values,我只能将一次变量定义为返回值。例如:

密新

.px-to-emz( @size, @base: @font-size-base ){
    @em: round( unit( (@size / @base), ~"em" ), 3 );
}

调用它:

.foo {
    font-size: @em;
    .px-to-emz(10, 16px);

    height: @em;
    .px-to-emz(200, 16px);
}

很好,如果你只想返回一个变量,但如果我想返回多个变量,我需要定义新的变量名。这是我理想的做法

密新

.px-to-ems( @size, @var: 'em', @base: @font-size-base ){
    ~'@{var}': round( unit( (@size / @base), ~"em" ), 3 );
}

调用它:

.foo {
    font-size: @font-size;
    .px-to-ems(10, 'font-size', 16px);

    height: @height;
    .px-to-ems(200, 'height', 16px);
}

1 个答案:

答案 0 :(得分:0)

#1

到目前为止,针对此问题的最着名解决方案是将每个mixin调用放入其自己的范围:

.px-to-ems(@size, @base: @font-size-base) {
    @-: round(unit((@size / @base), em), 3);
}

.foo {
    .-() {font-size: @-; .px-to-ems( 10, 16px)}
    .-() {height:    @-; .px-to-ems(200, 16px)}
    .-;
}

@-.-替换为您认为合适的标识符。

#2

另一种方法是使用最近添加的(Less 1.6.x)属性插值功能:

.px-to-ems(@property, @size, @base: @font-size-base) {
    @{property}: round(unit((@size / @base), em), 3);
}

.foo {
    .px-to-ems(font-size, 10, 16px);
    .px-to-ems(height,   200, 16px);
}

如果你只是需要将“功能”结果分配给一个属性,它比#1更干净。

相关问题