Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 是否使用scss类名获取已定义的变量?_Html_Css_Sass - Fatal编程技术网

Html 是否使用scss类名获取已定义的变量?

Html 是否使用scss类名获取已定义的变量?,html,css,sass,Html,Css,Sass,假设您有重复代码: $primary: white; $secondary: black; $success: green; $danger: red; $warning: yellow; &.primary-stripe { border-top-color: $primary; } &.secondary-stripe { border-top-color: $secondary; } &.success-stripe { border-top-co

假设您有重复代码:

$primary: white;
$secondary: black;
$success: green;
$danger: red;
$warning: yellow;

&.primary-stripe {
  border-top-color: $primary;
}

&.secondary-stripe {
  border-top-color: $secondary;
}

&.success-stripe {
  border-top-color: $success;
}

&.danger-stripe {
  border-top-color: $danger;
}

&.warning-stripe {
  border-top-color: $warning;
}
有没有一种方法可以通过基于已经存在的类名访问变量来简化它?比如说

&.[var]-stripe {
   border-top-color: $[var];
}
唯一棘手的部分是当$[var]不存在时会发生什么。我猜SCS可能会出错?

您可以使用以下方法:

$color_map: (
'primary': 'white',
'secondary': 'black',
'success': 'green',
'danger': 'red',
'warning': 'yellow'
);


.main_selector {
   @each $name, $color in $color_map {
      &.#{$name}-stripe {
        border-top-color: #{$color};
      }
   }
}
这将编译为:

.main_selector.primary-stripe {
  border-top-color: white;
}
.main_selector.secondary-stripe {
  border-top-color: black;
}
.main_selector.success-stripe {
  border-top-color: green;
}
.main_selector.danger-stripe {
  border-top-color: red;
}
.main_selector.warning-stripe {
  border-top-color: yellow;
}

你可以用你所有的颜色创建一张地图吗?如果是这样,您可以在地图中的颜色上循环。