如何使用多个参数进行sass颜色比较功能?

时间:2017-11-21 22:39:22

标签: css colors sass compass-sass sass-rails

当前colorcontrast功能仅与三种颜色进行比较。寻找最佳解决方案,使用@function colorcontrast($color, $rest...) {等多个参数构建color: colorcontrast(yellow, blue, orange, tomato, deekskyblue);,但不确定如何与所有列出的颜色进行比较。

@function brightness($color) {
  @return ((red($color) * .299) + (green($color) * .587) + (blue($color) * .114)) / 255 * 100%;
}
@function colorcontrast($color, $dark, $light) {
    $color-brightness: brightness($color);
    $light-text-brightness: brightness($light);
    $dark-text-brightness: brightness($dark);
    @return if(abs($color-brightness - $light-text-brightness) > abs($color-brightness - $dark-text-brightness), $light, $dark);
}

.my-div{
  padding: 1rem;
  background-color: yellow;
  color: colorcontrast(yellow, #000, #fff);
}

1 个答案:

答案 0 :(得分:1)

您只需要在循环中计算列表中所有颜色的对比度。并选择与基色具有最佳对比度的颜色。

@function brightness($color) {
  @return ((red($color) * .299) + (green($color) * .587) + (blue($color) * .114)) / 255 * 100%;
}

@function color-contrast($base-color, $colors...) { 
    // $colors... - means variadic arguments as Chris W says

    // Suppose that the best color is the first in the colors list
    $best-color: nth($colors, 1);
    $best-color-brightness: brightness($best-color);

    $base-color-brightness: brightness($base-color);

    @each $color in $colors {
      $color-brightness: brightness($color);

      // If the new color ($color) is more contrast than the previous one, 
      // remember it as the $best-color
      @if(abs($base-color-brightness - $color-brightness) > abs($base-color-brightness - $best-color-brightness)) {
        $best-color: $color;
        $best-color-brightness: $color-brightness;
      }
    }

    @return $best-color;
}

SassMeister demo
@each指令的Documentation