简体   繁体   中英

Write SASS loop with variables

I'm wondering is there is a way to write this:

    &: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);
    }

.. into a more useful loop, by putting [hover, focus, active] as values in both the &: -selector and the variables used in the SASS code. I've tried to use the #{map-get} structure, but without any success. Thanks for any tips!

You could use a map to define selector, states and values:

$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 output

.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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM