一个SCSS里mixin的使用例子
Mixins are the Sass equivalent of macros in other programming languages. If you’ve programmed before you could think of them as functions, procedures, or methods, but they aren’t technically any of these concepts because their function is to generate code at compile time not execute code at run time.
可以把mixins当成编程语言里的宏,但是技术上说,scss mixins用于在编译器生成代码,而不是在运行时执行代码。
一个例子:
a.button {
background: black;
color: white;
padding: 10px 20px;
@include border-radius(5px);
}
编译之后:
a.button {
background: black;
color: white;
padding: 10px 20px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
-khtml-border-radius: 5px;
border-radius: 5px;
}
I used the @include directive to tell Sass that I wanted to call out to a mixin.
使用@include指令,告诉sass,需要在css里call out mixin. 通过括号传递参数。
看下border-radius的实现代码:
@mixin border-radius($radius) {
-moz-border-radius: $radius;
-webkit-border-radius: $radius;
-ms-border-radius: $radius;
border-radius: $radius;
}
一个mixin传递默认参数的做法:
@mixin border-radius($radius: 5px) {
...
}
或者定义一个全局变量:
$default-border-radius: 5px !default;
@mixin border-radius($radius: $default-border-radius) {
...
}
scss mixin里还支持条件指令@if:
@mixin border-radius($radius: 5px, $moz: true, $webkit: true, $ms: true) {
@if $moz { -moz-border-radius: $radius; }
@if $webkit { -webkit-border-radius: $radius; }
@if $ms { -ms-border-radius: $radius; }
border-radius: $radius;
}
上面的用法叫做keyword argument.
这样,如果项目里我们不考虑对IE的支持,只需要下面这样写就行了:
@include border-radius($ms: false);
而不用这种繁琐的写法:
@include border-radius(5px, true, true, true);
也不需要按照顺序传递参数:
@include border-radius($ms: false, $radius: 10px);
- 点赞
- 收藏
- 关注作者
评论(0)