代码之家  ›  专栏  ›  技术社区  ›  Sm Yamashita

如何检查变量是否在Less like Sass的variable_exists($name)中设置

  •  1
  • Sm Yamashita  · 技术社区  · 9 年前

    我想把萨斯改成Less,但我遇到了问题。在Sass代码中有 variable_exists($name) 但Less不具有类似的功能。所以我转换了下面的代码

    萨斯

    .test {
        background: if(variable-exists(background), $small-font-size, red);
    }
    

    较少的

    .define-test(@background: red) {
        background: @background;
    }
    
    .test {
        .define-test(); 
    }
    

    它可以工作,但我有问题,如果它是复杂的代码。请告诉我如何在下面的Less中转换复杂的Sass代码:

    萨斯

    .test {
        font: if(variable-exists(font-size), $font-size, 100%)/#{if(variable-exists(line-height), $line-height, 1.5)};
    }
    

    提前谢谢。

    1 回复  |  直到 9 年前
        1
  •  2
  •   Community CDub    4 年前

    不要:

    虽然可以逐行转换此代码(使用 #1894 #1400 ),例如:

    // defaults:
    @font-size:   none;
    @line-height: none;
    
    // styles:
    .test {
       .-(@s,   @h) {@size: @s; @height: @h}
       .-(none, @h) {@size: @s}
       .-(@s, none) {@height: @h}
       .-(@font-size, @line-height);
       font: @font-size/@line-height;
    }
    
    // user/custom overrides (comment/uncomment to test):
    @font-size:   33px;
    @line-height: 5.55;
    

    Demo .


    做:

    实际上你 不要 如果你采用声明式的方式,那么根本不需要上述任何条件。正确的Less代码就这么简单:

    // defaults:
    @font-size:   100%;
    @line-height: 1.5;
    
    // styles:
    .test {
       font: @font-size/@line-height;
    }
    
    // user/custom overrides (comment/uncomment to test):
    @font-size:   33px;
    @line-height: 5.55;
    

    Demo .


    请注意,这些“配置”变量都不必是全局的。您可以使用命名空间变量覆盖两个全局默认值(如 this )也可以使用命名空间默认值(如 this ),等等。