if-statement - 在 Sass 中,使用插值的 if 语句始终求值为 true

标签 if-statement sass

我有一个 if/else 语句在 scss 的每个函数中运行。

如果背景等于白色,我基本上希望它使文本变为黑色

@debug 指令告诉我我的语句正确返回,但所有按钮在悬停时最终都会显示黑色文本颜色?我在这里错过了什么吗?

//variables
$brand-primary:             #37a2c6 !default;
$brand-success:             #39c66a !default;
$brand-info:                #5bc0de !default;
$brand-warning:             #f7901e !default;
$brand-danger:              #e42829 !default;
$brand-haze:                #9e50da !default;

$color-white:               #ffffff;
$color-black:               #232323;


//map
$colors: (
  ("danger", $brand-danger, $brand-success), ("warning", $brand-warning, $brand-haze), ("success", $brand-success, $brand-primary), ("primary", $brand-primary, $brand-success), ("haze", $brand-haze, $brand-warning), ("pure", $color-white, $color-black)
);

//function
@each $color in $colors {   

  .btn--hollow {
    background: none !important;
    &.btn-#{nth($color,1)} {
      color: #{nth($color,2)} !important;
      &:hover {
        background: #{nth($color,2)} !important;
        @if #{nth($color,2)} == '#ffffff' {
          color: $color-black !important;
          @debug #{nth($color,2)} == '#ffffff' ;
        } @else {
          color: $color-white !important;
        }

      }
    }
  }

} //end each

最佳答案

此处使用插值是将 @if 语句中的表达式转换为字符串。当您编写 @if 'somestring' {/* stuff */} 时,它的计算结果将始终为 true。

$color: #ffffff;
$foo: #{$color} == '#ffffff';
@debug $foo; // DEBUG: #ffffff == "#ffffff"
@debug type-of($foo); // DEBUG: string

$color: #000000;
$foo: #{$color} == '#ffffff';
@debug $foo; // DEBUG: #000000 == "#ffffff"
@debug type-of($foo); // DEBUG: string

尚不清楚这种行为是否是有意为之,但这是您应该不使用插值的众多原因之一,除非您确实需要将变量转换为字符串

$color: #ffffff;
$foo: $color == #ffffff;
@debug $foo; // DEBUG: true
@debug type-of($foo); // DEBUG: bool

$color: #000000;
$foo: $color == #ffffff;
@debug $foo; // DEBUG: false
@debug type-of($foo); // DEBUG: bool

关于if-statement - 在 Sass 中,使用插值的 if 语句始终求值为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34770040/

相关文章:

javascript - 我应该如何使用 jQuery 正确构建这个 "if"语句?

node.js - 不导出文件时,Webpack 无法正确渲染 sass

Angular 6 中的 Css 问题

css - 是否可以在不在服务器上安装任何东西的情况下使用 CSS 嵌套规则?

javascript - 我如何呈现条件样式(React + Sass)

html - SCSS : On hover div, 显示另一个 div

python - 创建一个字谜检查器

javascript - 替代一百万个 IF 语句

objective-c - int 不增加

c++ - 如何做一个 "if... then, but also if.... then but if neither do...."