Can I define a LESS mixin to generate a transition-property with a variable number of parameters?

前端 未结 4 1074
自闭症患者
自闭症患者 2020-12-14 19:40

I\'m introducing LESS to a large web app project to simplify my CSS. I\'ve got a few CSS rules which apply transitions to a varying number of properties, for example:

4条回答
  •  一向
    一向 (楼主)
    2020-12-14 20:06

    I've managed to figure it out thanks to Luke Page pointing me towards the ... syntax.

    The solution was to use the following:

    • ... to allow variable parameters
    • Backticks for JavaScript evaluation
    • Variable string interpolation
    • A ~ prefix to escape the resulting expression (i.e. stop LESS from enclosing it in a string)
    • Good old regular expressions

    Phew. Here's the resulting mixin:

    .transition-properties(...) {
        -webkit-transition-property: ~`"@{arguments}".replace(/[\[\]]/g, '')`;
    }
    

    And here's the full version with a complete set of browser extensions:

    .transition-properties(...) {
        @props: ~`"@{arguments}".replace(/[\[\]]/g, '')`;
        -webkit-transition-property: @props;
        -moz-transition-property: @props;
        -o-transition-property: @props;
        transition-property: @props;
    }
    

提交回复
热议问题