当前的colorcontrast
函数只比较三种颜色。寻找使用多个参数构建的最佳解决方案,例如 @function colorcontrast($color, $rest...) {
for 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);
}
最佳答案
您只需要循环计算列表中所有颜色的对比度。并选择与基色形成最佳对比的颜色。
@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 .
Documentation对于 @each
指令。
关于css - 如何使 sass 颜色比较函数具有多个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47423951/