【Less】实现可选参数以及各种AutopreFixer
世界Skill
Less和Sass、Scss、Stylus等都是CSS的预处理语言,比起CSS,它们更接近于一门完整的程序语言。变量、引用、函数、Mixin等,使得它们提供更强的逻辑功能来使得样式代码也可以复用、并且便于维护。Less相较其它几种,更加接近于CSS原生的思维模式和写法。本篇就我的使用心得,论述一下如何可选参数函数,以及介绍一些我实现的各种AutopreFixer,比如keyframes的AutopreFixer。
可选参数函数
在less中实现可选参数函数,只需要给参数设定一个不会用到的默认值,然后在内部检查是否为这个值并开分支即可:
.background(@all: undefined, @size: undefined, @pos: undefined, @re: undefined, @clip: undefined, @image: undefined, @color: undefined) {
.test();
.test() when not (@size = undefined) {
background-size: @size;
}
.test() when not (@pos = undefined) {
background-position: @pos;
}
.test() when not (@re = undefined) {
background-repeat: @re;
}
.test() when not (@clip = undefined) {
background-clip: @clip;
}
.test() when not (@image = undefined) {
background-image: @image;
}
.test() when not (@color = undefined) {
background-color: @color;
}
.test() when not (@all = undefined) {
background: @all;
}
}
如此,我们使用它时便可以达到如下效果:
.test {
.background(@size: cover, @color: green);
}
转换为:
.test {
background-size: cover;
background-color: green;
}
AutoPrefixer
主要用于处理浏览器兼容问题,一般的AutoPrefixer比较简单,主要利用将参数作为属性名的一部分的特性,比如这个:
.autoprefix-some(@name, @t) {
-webkit-@{name}: @t;
-moz-@{name}: @t;
-o-@{name}: @t;
@{name}: @t;
}
.autoprefix-transition(@t) {
.autoprefix-some(transition, @t);
}
下面代码:
.test {
.autoprefix-transition(all .5s esae-out);
}
将被转换为:
.test {
-webkit-transition: all .5s esae-out;
-moz-transition: all .5s esae-out;
-o-transition: all .5s esae-out;
transition: all .5s esae-out;
}
但如果想要实现keyframes
的AutopreFixer,就需要用到一些奇淫巧技了,比如字符串转移、拼接等,有点绕,自行体会吧:
.autoprefix-keyframe-transform(@name, @func, @t1, @t2, @t3: undefined, @use-prefix: true) {
.base(@prefix, @bind) {
.t1() {
@{prefix}@{func}: @t1;
}
.t2() {
@{prefix}@{func}: @t2;
}
.t3() {
@{prefix}@{func}: @t3;
}
@start: ~"@{bind}@@{prefix}keyframes @{name} { `'\n'` 0%";
@{start} { .t1(); }
.test() when (@t3 = undefined) {
100% { .t2(); }
}
.test() when not (@t3 = undefined) {
50% { .t2(); }
100% { .t3(); }
}
.test();
}
@end: ~"} `'\n'`";
.end() {
@{end} {.wtf {color: #fff}}
}
.base(~'', ~'');
.base(-o-, @end);
.base(-webkit-, @end);
.base(-moz-, @end);
.base(-ms-, @end);
.end();
}
下列代码:
.autoprefix-keyframe-transform(test, top, 30px, 60px, 30px);
将被转换为:
@keyframes test {
0% {
top: 30px
}
50% {
top: 60px
}
to {
top: 30px
}
}
@-webkit-keyframes test {
0% {
-webkit-top: 30px
}
50% {
-webkit-top: 60px
}
to {
-webkit-top: 30px
}
}
@-o-keyframes test {
0% {
-webkit-top: 30px
}
50% {
-webkit-top: 60px
}
to {
-webkit-top: 30px
}
}
@-moz-keyframes test {
0% {
-webkit-top: 30px
}
50% {
-webkit-top: 60px
}
to {
-webkit-top: 30px
}
}
@-ms-keyframes test {
0% {
-webkit-top: 30px
}
50% {
-webkit-top: 60px
}
to {
-webkit-top: 30px
}
}
点击查看评论