首页 文章

根据类在Sass中定义变量

提问于
浏览
2

我可以根据是否设置类来定义Sass中的变量 . 我需要做一些字体类型测试,并希望根据body类动态更改字体变量 $basicFont .

例如 . :

$basicFont: Arial, Helvetica, sans-serif;

body {
    &.verdana {
        $basicFont: Verdana, sans-serif;
    }
    &.tahoma {
        $basicFont: Tahoma, sans-serif;
    }    
}

是否有可能在Sass中处理这个问题?

1 回答

  • 2

    不,你要求的是要求Sass了解DOM . Sass只能直接编译到CSS,它永远不会发送到浏览器 .

    使用示例代码,您所做的只是每次都覆盖 $basicFont . 在3.4或更高版本中,您的变量将仅存在于其设置的块的范围内 .

    所以,你唯一真正的选择是使用mixins或extends .

    延伸

    这是有效的,但仅适用于非常简单的情况 .

    %font-family {
        &.one {
            font-family: Verdana, sans-serif;
        }
    
        &.two {
            font-family: Tahoma, sans-serif;
        }
    }
    
    .foo {
      @extend %font-family;
    }
    

    输出:

    .one.foo {
      font-family: Verdana, sans-serif;
    }
    .two.foo {
      font-family: Tahoma, sans-serif;
    }
    

    Mixin

    如果你想在哪里使用哪些变量进行更细粒度的控制,这是我建议的方法 .

    $global-themes:
        ( '.one': ('font-family': (Verdana, sans-serif), 'color': red)
        , '.two': ('font-family': (Tahoma, sans-serif), 'color': blue)
        );
    
    $current-theme: null; // don't touch, this is only used by the themer mixin
    
    @mixin themer($themes: $global-themes) {
        @each $selector, $theme in $themes {
            $current-theme: $theme !global;
            &#{$selector} {
                @content;
            }
        }
    }
    
    @function theme-value($property, $theme: $current-theme) {
        @return map-get($theme, $property);
    }
    
    .foo {
        @include themer {
            font-family: theme-value('font-family');
    
            a {
                color: theme-value('color');
            }
        }
    }
    

    输出:

    .foo.one {
      font-family: Verdana, sans-serif;
    }
    .foo.one a {
      color: red;
    }
    .foo.two {
      font-family: Tahoma, sans-serif;
    }
    .foo.two a {
      color: blue;
    }
    

相关问题