一个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當(dāng)成編程語(yǔ)言里的宏,但是技術(shù)上說(shuō),scss mixins用于在編譯器生成代碼,而不是在運(yùn)行時(shí)執(zhí)行代碼。
一個(gè)例子:
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. 通過(guò)括號(hào)傳遞參數(shù)。
看下border-radius的實(shí)現(xiàn)代碼:
@mixin border-radius($radius) {-moz-border-radius: $radius;-webkit-border-radius: $radius;-ms-border-radius: $radius;border-radius: $radius; }一個(gè)mixin傳遞默認(rèn)參數(shù)的做法:
@mixin border-radius($radius: 5px) {... }或者定義一個(gè)全局變量:
$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.
這樣,如果項(xiàng)目里我們不考慮對(duì)IE的支持,只需要下面這樣寫(xiě)就行了:
@include border-radius($ms: false);而不用這種繁瑣的寫(xiě)法:
@include border-radius(5px, true, true, true);也不需要按照順序傳遞參數(shù):
@include border-radius($ms: false, $radius: 10px);總結(jié)
以上是生活随笔為你收集整理的一个SCSS里mixin的使用例子的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 抖音火山版认证信息在哪
- 下一篇: SAP CRM Fiori 应用和 SA