Sass 中變量的作用域在過(guò)去幾年已經(jīng)發(fā)生了一些改變。直到最近,規(guī)則集和其他范圍內(nèi)聲明變量的作用域才默認(rèn)為本地。如果已經(jīng)存在同名的全局變量,則局部變量覆蓋全局變量。從 Sass 3.4 版本開始,Sass 已經(jīng)可以正確處理作用域的概念,并通過(guò)創(chuàng)建一個(gè)新的局部變量來(lái)代替。
本部分討論下全局變量的影子。當(dāng)在局部范圍內(nèi)(選擇器內(nèi)、函數(shù)內(nèi)、混合宏內(nèi)……)聲明一個(gè)已經(jīng)存在于全局范圍內(nèi)的變量時(shí),局部變量就成為了全局變量的影子?;旧?,局部變量只會(huì)在局部范圍內(nèi)覆蓋全局變量。
以下代碼片可以解析變量影子的概念。
// Initialize a global variable at root level.
$variable: 'initial value';
// Create a mixin that overrides that global variable.
@mixin global-variable-overriding {
$variable: 'mixin value' !global;
}
.local-scope::before {
// Create a local variable that shadows the global one.
$variable: 'local value';
// Include the mixin: it overrides the global variable.
@include global-variable-overriding;
// Print the variable’s value.
// It is the **local** one, since it shadows the global one.
content: $variable;
}
// Print the variable in another selector that does no shadowing.
// It is the **global** one, as expected.
.other-local-scope::before {
content: $variable;
}
更多建議: