作用域

2018-02-24 15:11 更新

Sass 中變量的作用域在過去幾年已經(jīng)發(fā)生了一些改變。直到最近,規(guī)則集和其他范圍內聲明變量的作用域才默認為本地。如果已經(jīng)存在同名的全局變量,則局部變量覆蓋全局變量。從 Sass 3.4 版本開始,Sass 已經(jīng)可以正確處理作用域的概念,并通過創(chuàng)建一個新的局部變量來代替。

本部分討論下全局變量的影子。當在局部范圍內(選擇器內、函數(shù)內、混合宏內……)聲明一個已經(jīng)存在于全局范圍內的變量時,局部變量就成為了全局變量的影子?;旧?,局部變量只會在局部范圍內覆蓋全局變量。

以下代碼片可以解析變量影子的概念。

// 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;
}
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號