用变量写SASS循环

时间:2017-01-30 11:26:01

标签: css loops sass

我想知道是否有办法写这个:

    &:hover#{map-get($selectors, notDisabled)} {
        background: $btn-default-hover-bg;
        border-color: $btn-default-hover-border;
        color: $btn-default-hover-color;
        @include box-shadow($btn-default-hover-boxshadow);
    }
    &:focus#{map-get($selectors, notDisabled)} {
        background: $btn-default-focus-bg;
        border-color: $btn-default-focus-border;
        color: $btn-default-focus-color;
        @include box-shadow($btn-default-focus-boxshadow);
    }
    &:active#{map-get($selectors, notDisabled)} {
        background: $btn-default-active-bg;
        border-color: $btn-default-active-border;
        color: $btn-default-active-color;
        @include box-shadow($btn-default-active-boxshadow);
    }

..进入一个更有用的循环,将[hover, focus, active]作为值放在&: - 选择器和SASS代码中使用的变量中。我试图使用#{map-get}结构,但没有任何成功。感谢您的任何提示!

1 个答案:

答案 0 :(得分:0)

您可以使用地图来定义选择器,状态和值:

$selectors:(    
  '.class': (    
    hover :(back: red,   color: red,   border: red,   shadow: 0 0 10px red  ),
    focus :(back: green, color: green, border: green, shadow: 0 0 10px green),
    active:(back: blue,  color: blue,  border: blue,  shadow: 0 0 10px blue )
  )    
  // .. add more selectors if needed    
);

@each $selector, $states in $selectors {    
  @each $state, $values in $states {    
    #{$selector}:#{$state} {     
      background:   map-get($values, back  );     
      color:        map-get($values, color );     
      border-color: map-get($values, border);    
      box-shadow:   map-get($values, shadow);    
    }      
  }    
}

CSS输出

.class:hover {
  background: red;
  color: red;
  border-color: red;
  box-shadow: 0 0 10px red;
}

.class:focus {
  background: green;
  color: green;
  border-color: green;
  box-shadow: 0 0 10px green;
}

.class:active {
  background: blue;
  color: blue;
  border-color: blue;
  box-shadow: 0 0 10px blue;
}