在 Sass 中,rgb()
和rgba()
是创建类型为color的变量的函数。当编译成 CSS 时,它看起来与函数语法相同。颜色类型是必要的,以使其有资格与颜色操作函数(lighten()、darken() 等)一起使用。
https://github.com/nex3/sass/blob/ab4b3b918bfa1fc77a9c4378e199ca1ed6f1704c/lib/sass/script/functions.rb#L366
# Creates a {Color} object from red, green, and blue values.
#
# @param red [Number]
# A number between 0 and 255 inclusive,
# or between 0% and 100% inclusive
# @param green [Number]
# A number between 0 and 255 inclusive,
# or between 0% and 100% inclusive
# @param blue [Number]
# A number between 0 and 255 inclusive,
# or between 0% and 100% inclusive
# @see #rgba
# @return [Color]
def rgb(red, green, blue)
assert_type red, :Number
assert_type green, :Number
assert_type blue, :Number
Color.new([red, green, blue].map do |c|
v = c.value
if c.numerator_units == ["%"] && c.denominator_units.empty?
v = Sass::Util.check_range("Color value", 0..100, c, '%')
v * 255 / 100.0
else
Sass::Util.check_range("Color value", 0..255, c)
end
end)
end
declare :rgb, [:red, :green, :blue]
# @see #rgb
# @overload rgba(red, green, blue, alpha)
# Creates a {Color} object from red, green, and blue values,
# as well as an alpha channel indicating opacity.
#
# @param red [Number]
# A number between 0 and 255 inclusive
# @param green [Number]
# A number between 0 and 255 inclusive
# @param blue [Number]
# A number between 0 and 255 inclusive
# @param alpha [Number]
# A number between 0 and 1
# @return [Color]
#
# @overload rgba(color, alpha)
# Sets the opacity of a color.
#
# @example
# rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5)
# rgba(blue, 0.2) => rgba(0, 0, 255, 0.2)
#
# @param color [Color]
# @param alpha [Number]
# A number between 0 and 1
# @return [Color]
def rgba(*args)
case args.size
when 2
color, alpha = args
assert_type color, :Color
assert_type alpha, :Number
Sass::Util.check_range('Alpha channel', 0..1, alpha)
color.with(:alpha => alpha.value)
when 4
red, green, blue, alpha = args
rgba(rgb(red, green, blue), alpha)
else
raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
end
end
declare :rgba, [:red, :green, :blue, :alpha]
declare :rgba, [:color, :alpha]
该rgb()
函数必须恰好有 3 个参数。rgba()
函数必须恰好有 2 或 4 个参数,最后一个参数是 0 到 1 之间的值。