跳至内容

内置函数

颜色函数

red(color[, value])

返回给定 color 的红色分量,或将红色分量设置为可选的第二个 value 参数。

red(#c00)
// => 204

red(#000, 255)
// => #f00
red(#c00)
// => 204

red(#000, 255)
// => #f00

green(color[, value])

返回给定 color 的绿色分量,或将绿色分量设置为可选的第二个 value 参数。

green(#0c0)
// => 204

green(#000, 255)
// => #0f0
green(#0c0)
// => 204

green(#000, 255)
// => #0f0

blue(color[, value])

返回给定 color 的蓝色分量,或将蓝色分量设置为可选的第二个 value 参数。

blue(#00c)
// => 204

blue(#000, 255)
// => #00f
blue(#00c)
// => 204

blue(#000, 255)
// => #00f

alpha(color[, value])

返回给定 color 的 alpha 分量,或将 alpha 分量设置为可选的第二个 value 参数。

alpha(#fff)
// => 1

alpha(rgba(0,0,0,0.3))
// => 0.3

alpha(#fff, 0.5)
// => rgba(255,255,255,0.5)
alpha(#fff)
// => 1

alpha(rgba(0,0,0,0.3))
// => 0.3

alpha(#fff, 0.5)
// => rgba(255,255,255,0.5)

dark(color)

检查 color 是否为深色

dark(black)
// => true

dark(#005716)
// => true

dark(white)
// => false
dark(black)
// => true

dark(#005716)
// => true

dark(white)
// => false

light(color)

检查 color 是否浅色

light(black)
// => false

light(white)
// => true

light(#00FF40)
// => true
light(black)
// => false

light(white)
// => true

light(#00FF40)
// => true

hue(color[, value])

返回给定 color 的色调,或将色调组件设置为可选的第二个 value 参数。

hue(hsl(50deg, 100%, 80%))
// => 50deg

hue(#00c, 90deg)
// => #6c0
hue(hsl(50deg, 100%, 80%))
// => 50deg

hue(#00c, 90deg)
// => #6c0

saturation(color[, value])

返回给定 color 的饱和度,或将饱和度组件设置为可选的第二个 value 参数。

saturation(hsl(50deg, 100%, 80%))
// => 100%

saturation(#00c, 50%)
// => #339
saturation(hsl(50deg, 100%, 80%))
// => 100%

saturation(#00c, 50%)
// => #339

lightness(color[, value])

返回给定 color 的亮度,或将亮度组件设置为可选的第二个 value 参数。

lightness(hsl(50deg, 100%, 80%))
// => 80%

lightness(#00c, 80%)
// => #99f
lightness(hsl(50deg, 100%, 80%))
// => 80%

lightness(#00c, 80%)
// => #99f

hsla(color | h,s,l,a)

将给定的 color 转换为 HSLA 节点或 h、s、l、a 组件值。

hsla(10deg, 50%, 30%, 0.5)
// => HSLA

hsla(#ffcc00)
// => HSLA
hsla(10deg, 50%, 30%, 0.5)
// => HSLA

hsla(#ffcc00)
// => HSLA

hsl(color | h,s,l)

将给定的 color 转换为 HSLA 节点或 h、s、l、a 组件值。

hsl(10, 50, 30)
// => HSLA

hsl(#ffcc00)
// => HSLA
hsl(10, 50, 30)
// => HSLA

hsl(#ffcc00)
// => HSLA

rgba(color | r,g,b,a)

从 r、g、b、a 通道返回 RGBA,或提供 color 来调整 alpha。

rgba(255,0,0,0.5)
// => rgba(255,0,0,0.5)

rgba(255,0,0,1)
// => #ff0000

rgba(#ffcc00, 0.5)
// rgba(255,204,0,0.5)
rgba(255,0,0,0.5)
// => rgba(255,0,0,0.5)

rgba(255,0,0,1)
// => #ff0000

rgba(#ffcc00, 0.5)
// rgba(255,204,0,0.5)

另外,Stylus 还支持 #rgba#rrggbbaa 表示法

#fc08
// => rgba(255,204,0,0.5)

#ffcc00ee
// => rgba(255,204,0,0.9)
#fc08
// => rgba(255,204,0,0.5)

#ffcc00ee
// => rgba(255,204,0,0.9)

rgb(color | r,g,b)

从 r、g、b 通道返回 RGBA 或转换为 RGBA 节点。

rgb(255,204,0)
// => #ffcc00

rgb(#fff)
// => #fff
rgb(255,204,0)
// => #ffcc00

rgb(#fff)
// => #fff

blend(top[, bottom])

使用普通混合将给定的 top 颜色与 bottom 颜色混合。bottom 参数是可选的,默认为 #fff

blend(rgba(#FFF, 0.5), #000)
// => #808080

blend(rgba(#FFDE00,.42), #19C261)
// => #7ace38

blend(rgba(lime, 0.5), rgba(red, 0.25))
// => rgba(128,128,0,0.625)
blend(rgba(#FFF, 0.5), #000)
// => #808080

blend(rgba(#FFDE00,.42), #19C261)
// => #7ace38

blend(rgba(lime, 0.5), rgba(red, 0.25))
// => rgba(128,128,0,0.625)

lighten(color, amount)

将给定的 color 提亮 amount

此函数对单位敏感;它支持百分比,例如,如下所示

lighten(#2c2c2c, 30)
// => #787878

lighten(#2c2c2c, 30%)
// => #393939
lighten(#2c2c2c, 30)
// => #787878

lighten(#2c2c2c, 30%)
// => #393939

darken(color, amount)

将给定的 color 加深 amount

此函数对单位敏感;它支持百分比,例如,如下所示

darken(#D62828, 30)
// => #551010

darken(#D62828, 30%)
// => #961c1c
darken(#D62828, 30)
// => #551010

darken(#D62828, 30%)
// => #961c1c

desaturate(color, amount)

将给定的 color 去饱和 amount

desaturate(#f00, 40%)
// => #c33
desaturate(#f00, 40%)
// => #c33

saturate(color, amount)

将给定的 color 饱和 amount

saturate(#c33, 40%)
// => #f00
saturate(#c33, 40%)
// => #f00

complement(color)

提供互补色。相当于将色相旋转 180deg

complement(#fd0cc7)
// => #0cfd42
complement(#fd0cc7)
// => #0cfd42

invert(color)

反转颜色。红色、绿色和蓝色值被反转。不改变不透明度。

invert(#d62828)
// => #29d7d7
invert(#d62828)
// => #29d7d7

spin(color, amount)

将给定 color 的色相旋转 amount

spin(#ff0000, 90deg)
// => #80ff00
spin(#ff0000, 90deg)
// => #80ff00

grayscale(color)

提供给定颜色的灰度等效值。相当于 desaturate(color, 100%)

grayscale(#fd0cc7)
// => #0cfd42
grayscale(#fd0cc7)
// => #0cfd42

mix(color1, color2[, amount])

按照给定量混合两种颜色。amount 是可选的,默认为 50%

mix(#000, #fff, 30%)
// => #b2b2b2
mix(#000, #fff, 30%)
// => #b2b2b2

tint(color, amount)

将给定颜色与白色混合。

tint(#fd0cc7,66%)
// => #feaceb
tint(#fd0cc7,66%)
// => #feaceb

shade(color, amount)

将给定颜色与黑色混合。

shade(#fd0cc7,66%)
// => #560443
shade(#fd0cc7,66%)
// => #560443

luminosity(color)

返回给定 color相对亮度

luminosity(white)
// => 1

luminosity(#000)
// => 0

luminosity(red)
// => 0.2126
luminosity(white)
// => 1

luminosity(#000)
// => 0

luminosity(red)
// => 0.2126

contrast(top[, bottom])

返回 topbottom 颜色之间的对比度比对象,基于 Lea Verou 的“对比度比”工具的底层脚本

第二个参数是可选的,默认为 #fff

返回的对象中的主键是 ratio,它还有 minmax 值,这些值仅当 bottom 颜色为透明时才与 ratio 不同。在这种情况下,error 还包含误差范围。

contrast(#000, #fff).ratio
// => 21
contrast(#000, rgba(#FFF, 0.5))
// => { "ratio": "13.15;", "error": "-7.85", "min": "5.3", "max": "21" }
contrast(#000, #fff).ratio
// => 21
contrast(#000, rgba(#FFF, 0.5))
// => { "ratio": "13.15;", "error": "-7.85", "min": "5.3", "max": "21" }

transparentify(top[, bottom, alpha])

返回给定 top 颜色的透明版本,就像它与给定的 bottom 颜色(或最接近它的颜色,如果可能的话)混合一样。

第二个参数是可选的,默认为 #fff

第三个参数是可选的,它会覆盖自动检测到的 alpha。

transparentify(#808080)
// => rgba(0,0,0,0.5)

transparentify(#414141, #000)
// => rgba(255,255,255,0.25)

transparentify(#91974C, #F34949, 0.5)
// => rgba(47,229,79,0.5)
transparentify(#808080)
// => rgba(0,0,0,0.5)

transparentify(#414141, #000)
// => rgba(255,255,255,0.25)

transparentify(#91974C, #F34949, 0.5)
// => rgba(47,229,79,0.5)

路径函数

basename(path[, ext])

返回 path 的基本名称,(可选)移除 ext 扩展名。

basename('images/foo.png')
// => "foo.png"

basename('images/foo.png', '.png')
// => "foo"
basename('images/foo.png')
// => "foo.png"

basename('images/foo.png', '.png')
// => "foo"

dirname(路径)

返回路径的目录名。

dirname('images/foo.png')
// => "images"
dirname('images/foo.png')
// => "images"

extname(路径)

返回路径的文件扩展名,包括点。

extname('images/foo.png')
// => ".png"
extname('images/foo.png')
// => ".png"

pathjoin(...)

执行路径连接。

pathjoin('images', 'foo.png')
// => "images/foo.png"

path = 'images/foo.png'
ext = extname(path)
pathjoin(dirname(path), basename(path, ext) + _thumb + ext)
// => 'images/foo_thumb.png'
pathjoin('images', 'foo.png')
// => "images/foo.png"

path = 'images/foo.png'
ext = extname(path)
pathjoin(dirname(path), basename(path, ext) + _thumb + ext)
// => 'images/foo_thumb.png'

列表/哈希函数

push(expr, args...)

将给定的args推送到expr

nums = 1 2
push(nums, 3, 4, 5)

nums
// => 1 2 3 4 5
nums = 1 2
push(nums, 3, 4, 5)

nums
// => 1 2 3 4 5

别名为append()

pop(expr)

expr中弹出值。

nums = 4 5 3 2 1
num = pop(nums)

nums
// => 4 5 3 2
num
// => 1
nums = 4 5 3 2 1
num = pop(nums)

nums
// => 4 5 3 2
num
// => 1

shift(expr)

expr中移动元素。

nums = 4 5 3 2 1
num = shift(nums)

nums
// => 5 3 2 1
num
// => 4
nums = 4 5 3 2 1
num = shift(nums)

nums
// => 5 3 2 1
num
// => 4

unshift(expr, args...)

将给定的args插入到expr

nums = 4 5
unshift(nums, 3, 2, 1)

nums
// => 1 2 3 4 5
nums = 4 5
unshift(nums, 3, 2, 1)

nums
// => 1 2 3 4 5

别名为prepend()

index(列表, 值)

返回列表中的(以 0 为基准的)索引。

list = 1 2 3

index(list, 2)
// => 1

index(1px solid red, red)
// => 2
list = 1 2 3

index(list, 2)
// => 1

index(1px solid red, red)
// => 2

keys(对)

返回给定中的键

pairs = (one 1) (two 2) (three 3)
keys(pairs)
// => one two three
pairs = (one 1) (two 2) (three 3)
keys(pairs)
// => one two three

values(对)

返回给定中的值

pairs = (one 1) (two 2) (three 3)
values(pairs)
// => 1 2 3
pairs = (one 1) (two 2) (three 3)
values(pairs)
// => 1 2 3

list-separator(列表)

返回给定列表的分隔符。

list1 = a b c
list-separator(list1)
// => ' '

list2 = a, b, c
list-separator(list2)
// => ','
list1 = a b c
list-separator(list1)
// => ' '

list2 = a, b, c
list-separator(list2)
// => ','

length([expr])

带括号的表达式可以作为元组,length() 函数返回此类表达式的长度。

length((1 2 3 4))
// => 4

length((1 2))
// => 2

length((1))
// => 1

length(())
// => 0

length(1 2 3)
// => 3

length(1)
// => 1

length()
// => 0
length((1 2 3 4))
// => 4

length((1 2))
// => 2

length((1))
// => 1

length(())
// => 0

length(1 2 3)
// => 3

length(1)
// => 1

length()
// => 0

last(expr)

返回给定expr中的最后一个

nums = 1 2 3
last(nums)
last(1 2 3)
// => 3

list = (one 1) (two 2) (three 3)
last(list)
// => (three 3)
nums = 1 2 3
last(nums)
last(1 2 3)
// => 3

list = (one 1) (two 2) (three 3)
last(list)
// => (three 3)

单位函数

typeof(节点)

返回节点的类型,类型为字符串。

type(12)
// => 'unit'

typeof(12)
// => 'unit'

typeof(#fff)
// => 'rgba'

type-of(#fff)
// => 'rgba'
type(12)
// => 'unit'

typeof(12)
// => 'unit'

typeof(#fff)
// => 'rgba'

type-of(#fff)
// => 'rgba'

别名为type-oftype

unit(val[, type])

返回一个字符串,表示val的类型或空字符串,或在不进行单位转换的情况下分配给定的type

unit(10)
// => ''

unit(15in)
// => 'in'

unit(15%, 'px')
// => 15px

unit(15%, px)
// => 15px
unit(10)
// => ''

unit(15in)
// => 'in'

unit(15%, 'px')
// => 15px

unit(15%, px)
// => 15px

percentage(num)

num转换为百分比。

percentage(.5)
// => 50%

percentage(4 / 100)
// => 4%
percentage(.5)
// => 50%

percentage(4 / 100)
// => 4%

数学函数

abs(unit)

abs(-5px)
// => 5px

abs(5px)
// => 5px
abs(-5px)
// => 5px

abs(5px)
// => 5px

ceil(unit)

ceil(5.5in)
// => 6in
ceil(5.5in)
// => 6in

floor(unit)

floor(5.6px)
// => 5px
floor(5.6px)
// => 5px

round(unit)

round(5.5px)
// => 6px

round(5.4px)
// => 5px
round(5.5px)
// => 6px

round(5.4px)
// => 5px

注意:所有舍入函数都可以接受可选的precision参数——您可以传递小数点后要保留的位数

ceil(5.52px,1)
// => 5.6px

floor(5.57px,1)
// => 5.5px

round(5.52px,1)
// => 5.5px
ceil(5.52px,1)
// => 5.6px

floor(5.57px,1)
// => 5.5px

round(5.52px,1)
// => 5.5px

sin(角度)

返回给定角度的正弦值。如果角度以度数单位给出,如45deg,则将其视为度数,否则将其视为弧度。

sin(30deg)
// => 0.5

sin(3*PI/4)
// => 0.707106781
sin(30deg)
// => 0.5

sin(3*PI/4)
// => 0.707106781

cos(角度)

返回给定角度的余弦值。如果角度以度数单位给出,如45deg,则将其视为度数,否则将其视为弧度。

cos(180deg)
// => -1
cos(180deg)
// => -1

tan(angle)

返回给定angle的正切值。如果角度以度为单位,如45deg,则将其视为度,否则将其视为弧度。

tan(45deg)
// => 1

tan(90deg)
// => Infinity
tan(45deg)
// => 1

tan(90deg)
// => Infinity

min(a, b)

min(1, 5)
// => 1
min(1, 5)
// => 1

max(a, b)

max(1, 5)
// => 5
max(1, 5)
// => 5

even(unit)

even(6px)
// => true
even(6px)
// => true

odd(unit)

odd(5mm)
// => true
odd(5mm)
// => true

sum(nums)

sum(1 2 3)
// => 6
sum(1 2 3)
// => 6

avg(nums)

avg(1 2 3)
// => 2
avg(1 2 3)
// => 2

range(start, stop[, step])

返回从startstop(包括)的单位列表,按给定的step步长。

如果省略,则step参数默认为1。它不能为0

range(1, 6)
// equals to `1..6`
// 1 2 3 4 5 6

range(1, 6, 2)
// 1 3 5

range(-6, -1, 2)
// -6 -4 -2

range(1px, 3px, 0.5px)
// 1px 1.5px 2px 2.5px 3px
range(1, 6)
// equals to `1..6`
// 1 2 3 4 5 6

range(1, 6, 2)
// 1 3 5

range(-6, -1, 2)
// -6 -4 -2

range(1px, 3px, 0.5px)
// 1px 1.5px 2px 2.5px 3px

它最常用于for循环中

for i in range(10px, 50px, 10)
  .col-{i}
    width: i
for i in range(10px, 50px, 10)
  .col-{i}
    width: i

产生

.col-10 {
  width: 10px;
}
.col-20 {
  width: 20px;
}
.col-30 {
  width: 30px;
}
.col-40 {
  width: 40px;
}
.col-50 {
  width: 50px;
}
.col-10 {
  width: 10px;
}
.col-20 {
  width: 20px;
}
.col-30 {
  width: 30px;
}
.col-40 {
  width: 40px;
}
.col-50 {
  width: 50px;
}

base-convert(num, base, width)

返回一个Literal num,它被转换为提供的base,并用width个零填充。

宽度默认为2

base-convert(1, 10, 3)
// => 001

base-convert(14, 16, 1)
// => e

base-convert(42, 2)
// => 101010
base-convert(1, 10, 3)
// => 001

base-convert(14, 16, 1)
// => e

base-convert(42, 2)
// => 101010

字符串函数

match(pattern, string[, flags])

返回pattern(正则表达式)在string中的任何匹配项。

match('^(height|width)?([<>=]{1,})(.*)', 'height>=1024px')
// => 'height>=1024px' 'height' '>=' '1024px'

match('^foo(?:bar)?', 'foo')
// => 'foo'

match('^foo(?:bar)?', 'foobar')
// => 'foobar'

match('^foo(?:bar)?', 'bar')
// => null

match('ain', 'The rain in SPAIN stays mainly in the plain')
// => 'ain'

match('ain', 'The rain in SPAIN stays mainly in the plain', g)
// => 'ain' 'ain' 'ain'

match('ain', 'The rain in SPAIN stays mainly in the plain', 'gi')
// => 'ain' 'AIN' 'ain' 'ain'
match('^(height|width)?([<>=]{1,})(.*)', 'height>=1024px')
// => 'height>=1024px' 'height' '>=' '1024px'

match('^foo(?:bar)?', 'foo')
// => 'foo'

match('^foo(?:bar)?', 'foobar')
// => 'foobar'

match('^foo(?:bar)?', 'bar')
// => null

match('ain', 'The rain in SPAIN stays mainly in the plain')
// => 'ain'

match('ain', 'The rain in SPAIN stays mainly in the plain', g)
// => 'ain' 'ain' 'ain'

match('ain', 'The rain in SPAIN stays mainly in the plain', 'gi')
// => 'ain' 'AIN' 'ain' 'ain'

replace(pattern, replacement, val)

返回字符串val,在用replacement替换所有pattern匹配项后。

replace(i, e, 'griin')
// => 'green'

replace(i, e, griin)
// => #008000
replace(i, e, 'griin')
// => 'green'

replace(i, e, griin)
// => #008000

join(delim, vals...)

delim连接给定的vals

join(' ', 1 2 3)
// => "1 2 3"

join(',', 1 2 3)
// => "1,2,3"

join(', ', foo bar baz)
// => "foo, bar, baz"

join(', ', foo, bar, baz)
// => "foo, bar, baz"

join(', ', 1 2, 3 4, 5 6)
// => "1 2, 3 4, 5 6"
join(' ', 1 2 3)
// => "1 2 3"

join(',', 1 2 3)
// => "1,2,3"

join(', ', foo bar baz)
// => "foo, bar, baz"

join(', ', foo, bar, baz)
// => "foo, bar, baz"

join(', ', 1 2, 3 4, 5 6)
// => "1 2, 3 4, 5 6"

split(delim, val)

split()方法通过将字符串分成子字符串来将字符串或标识符拆分为字符串列表。

split(_, bar1_bar2_bar3)
// => bar1 bar2 bar3

split(_, 'bar1_bar2_bar3')
// => 'bar1' 'bar2' 'bar3'
split(_, bar1_bar2_bar3)
// => bar1 bar2 bar3

split(_, 'bar1_bar2_bar3')
// => 'bar1' 'bar2' 'bar3'

substr(val, start, length)

substr()方法返回从指定位置开始到指定字符数的字符串中的字符。

substr(ident, 1, 2)
// => de

substr('string', 1, 2)
// => 'tr'

val = dredd
substr(substr(val, 1), 0, 3)
// => #f00
substr(ident, 1, 2)
// => de

substr('string', 1, 2)
// => 'tr'

val = dredd
substr(substr(val, 1), 0, 3)
// => #f00

slice(val, start[, end])

slice()方法提取字符串/列表的一部分并返回一个新的字符串/列表。

slice('lorem' 'ipsum' 'dolor', 1, 2)
slice('lorem' 'ipsum' 'dolor', 1, -1)
// => 'ipsum'

slice('lorem ipsum', 1, 5)
// => 'orem'
slice(rredd, 1, -1)
// => #f00

slice(1px solid black, 1)
// => solid #000
slice('lorem' 'ipsum' 'dolor', 1, 2)
slice('lorem' 'ipsum' 'dolor', 1, -1)
// => 'ipsum'

slice('lorem ipsum', 1, 5)
// => 'orem'
slice(rredd, 1, -1)
// => #f00

slice(1px solid black, 1)
// => solid #000

unquote(str | ident)

取消引用给定的 str,并将其作为 Literal 节点返回。

unquote("sans-serif")
// => sans-serif

unquote(sans-serif)
// => sans-serif

unquote('1px / 2px')
// => 1px / 2px
unquote("sans-serif")
// => sans-serif

unquote(sans-serif)
// => sans-serif

unquote('1px / 2px')
// => 1px / 2px

convert(str)

类似于 unquote(),但尝试将给定的 str 转换为 Stylus 节点。

unit = convert('40px')
typeof(unit)
// => 'unit'

color = convert('#fff')
typeof(color)
// => 'rgba'

foo = convert('foo')
typeof(foo)
// => 'ident'
unit = convert('40px')
typeof(unit)
// => 'unit'

color = convert('#fff')
typeof(color)
// => 'rgba'

foo = convert('foo')
typeof(foo)
// => 'ident'

s(fmt, ...)

s() 函数类似于 unquote(),因为它返回 Literal 节点。但是,它接受类似于 C 语言 sprintf() 的格式字符串。

目前,唯一的说明符是 %s

s('bar()');
// => bar()

s('bar(%s)', 'baz');
// => bar("baz")

s('bar(%s)', baz);
// => bar(baz)

s('bar(%s)', 15px);
// => bar(15px)

s('rgba(%s, %s, %s, 0.5)', 255, 100, 50);
// => rgba(255, 100, 50, 0.5)

s('bar(%Z)', 15px);
// => bar(%Z)

s('bar(%s, %s)', 15px);
// => bar(15px, null)
s('bar()');
// => bar()

s('bar(%s)', 'baz');
// => bar("baz")

s('bar(%s)', baz);
// => bar(baz)

s('bar(%s)', 15px);
// => bar(15px)

s('rgba(%s, %s, %s, 0.5)', 255, 100, 50);
// => rgba(255, 100, 50, 0.5)

s('bar(%Z)', 15px);
// => bar(%Z)

s('bar(%s, %s)', 15px);
// => bar(15px, null)

查看 % 字符串运算符以获取等效的行为。

实用程序函数

called-from 属性

called-from 属性包含当前函数被调用的函数列表,按相反的顺序排列(第一个项目是最深层的函数)。

foo()
  bar()

bar()
  baz()

baz()
  return called-from

foo()
// => bar foo
foo()
  bar()

bar()
  baz()

baz()
  return called-from

foo()
// => bar foo

current-media()

current-media() 函数返回当前块的 @media 规则的字符串(如果块上方没有 @media,则返回 '')。

@media only screen and (min-width: 1024px)
  current-media()
// => '@media (only screen and (min-width: (1024px)))'
@media only screen and (min-width: 1024px)
  current-media()
// => '@media (only screen and (min-width: (1024px)))'

+cache(keys...)

+cache 是一个非常强大的内置函数,允许您创建自己的“可缓存”混合。

“可缓存混合”是一种在第一次调用时将内容应用于给定选择器的混合,但在第二次调用时使用相同的参数@extend第一个调用的选择器。

size($width, $height = $width)
  +cache('w' + $width)
    width: $width
  +cache('h' + $height)
    height: $height

.a
  size: 10px 20px
.b
  size: 10px 2em
.c
  size: 1px 2em
size($width, $height = $width)
  +cache('w' + $width)
    width: $width
  +cache('h' + $height)
    height: $height

.a
  size: 10px 20px
.b
  size: 10px 2em
.c
  size: 1px 2em

将产生

.a,
.b {
  width: 10px;
}
.a {
  height: 20px;
}
.b,
.c {
  height: 2em;
}
.c {
  width: 1px;
}
.a,
.b {
  width: 10px;
}
.a {
  height: 20px;
}
.b,
.c {
  height: 2em;
}
.c {
  width: 1px;
}

查看选择器如何按所用属性分组在一起。

+prefix-classes(prefix)

Stylus 带有一个块混合 prefix-classes,可用于为任何给定 Stylus 块内的类添加前缀。例如

+prefix-classes('foo-')
  .bar
    width: 10px
+prefix-classes('foo-')
  .bar
    width: 10px

产生

.foo-bar {
  width: 10px;
}
.foo-bar {
  width: 10px;
}

lookup(name)

允许查找作为字符串传递的变量 name 的值。如果变量未定义,则返回 null

当您需要获取动态生成名称的变量的值时很有用

font-size-1 = 10px
font-size-2 = 20px
font-size-3 = 30px

for i in 1..3
  .text-{i}
    font-size: lookup('font-size-' + i)
font-size-1 = 10px
font-size-2 = 20px
font-size-3 = 30px

for i in 1..3
  .text-{i}
    font-size: lookup('font-size-' + i)

产生

.text-1 {
  font-size: 10px;
}
.text-2 {
  font-size: 20px;
}
.text-3 {
  font-size: 30px;
}
.text-1 {
  font-size: 10px;
}
.text-2 {
  font-size: 20px;
}
.text-3 {
  font-size: 30px;
}

define(name, expr[, global])

允许创建或覆盖具有给定 name(作为字符串传递)的变量到当前作用域(如果 global 为 true,则为全局作用域)。

BIF 在需要在变量名中插入时很有用

prefix = 'border'
border = { color: #000, length: 1px, style: solid }

for prop, val in border
  define(prefix + '-' + prop, val)

body
  border: border-length border-style border-color
prefix = 'border'
border = { color: #000, length: 1px, style: solid }

for prop, val in border
  define(prefix + '-' + prop, val)

body
  border: border-length border-style border-color

生成

body {
  border: 1px solid #000;
}
body {
  border: 1px solid #000;
}

operate(op, left, right)

leftright 操作数执行给定的 op

op = '+'
operate(op, 15, 5)
// => 20
op = '+'
operate(op, 15, 5)
// => 20

selector()

返回已编译的当前选择器,如果在根级别调用,则返回 &

.foo
  selector()
// => '.foo'

.foo
  &:hover
    selector()
// '.foo:hover'
.foo
  selector()
// => '.foo'

.foo
  &:hover
    selector()
// '.foo:hover'

selector-exists(selector)

如果 selector 存在,则返回 true。

.foo
  color red

  a
    font-size 12px

selector-exists('.foo') // true
selector-exists('.foo a') // true
selector-exists('.foo li') // false
selector-exists('.bar') // false
.foo
  color red

  a
    font-size 12px

selector-exists('.foo') // true
selector-exists('.foo a') // true
selector-exists('.foo li') // false
selector-exists('.bar') // false

此方法不考虑当前上下文含义

.foo
  color red

  a
    font-size 12px

  selector-exists('a') // false
  selector-exists(selector() + ' a') // true
.foo
  color red

  a
    font-size 12px

  selector-exists('a') // false
  selector-exists(selector() + ' a') // true

opposite-position(positions)

返回给定 positions 的相反值。

opposite-position(right)
// => left

opposite-position(top left)
// => bottom right

opposite-position('top' 'left')
// => bottom right
opposite-position(right)
// => left

opposite-position(top left)
// => bottom right

opposite-position('top' 'left')
// => bottom right

image-size(path)

返回在 path 处找到的图像的 widthheight。查找方式与 @import 相同,受 paths 设置更改。

width(img)
  return image-size(img)[0]

height(img)
  return image-size(img)[1]

image-size('tux.png')
// => 405px 250px

image-size('tux.png')[0] == width('tux.png')
// => true
width(img)
  return image-size(img)[0]

height(img)
  return image-size(img)[1]

image-size('tux.png')
// => 405px 250px

image-size('tux.png')[0] == width('tux.png')
// => true

embedurl(path[, encoding])

返回内联图像作为 url() 文字,并使用 encoding 编码。

(可用编码:base64(默认)和 utf8)。

background: embedurl('logo.png')
// => background: url("data:image/png;base64,…")

background: embedurl('logo.svg', 'utf8')
// => background: url("data:image/svg+xml;charset=utf-8,…")
background: embedurl('logo.png')
// => background: url("data:image/png;base64,…")

background: embedurl('logo.svg', 'utf8')
// => background: url("data:image/svg+xml;charset=utf-8,…")

add-property(name, expr)

将属性 name 和给定的 expr 添加到最近的块。

例如

something()
  add-property('bar', 1 2 3)
  s('bar')

body
  foo: something()
something()
  add-property('bar', 1 2 3)
  s('bar')

body
  foo: something()

生成

body {
  bar: 1 2 3;
  foo: bar;
}
body {
  bar: 1 2 3;
  foo: bar;
}

接下来,“神奇”的 current-property 局部变量开始发挥作用。此变量可自动用于函数主体,并包含一个表达式,其中包含当前属性的名称和值。

例如,如果我们使用 p() 检查此局部变量,则会得到以下内容

p(current-property)
// => "foo" (foo __CALL__ bar baz)

p(current-property[0])
// => "foo"

p(current-property[1])
// => foo __CALL__ bar baz
p(current-property)
// => "foo" (foo __CALL__ bar baz)

p(current-property[0])
// => "foo"

p(current-property[1])
// => foo __CALL__ bar baz

使用 current-property,我们可以进一步研究我们的示例,并使用新值复制属性,并添加条件以确保仅在属性值中使用该函数。

something(n)
  if current-property
    add-property(current-property[0], s('-webkit-something(%s)', n))
    add-property(current-property[0], s('-moz-something(%s)', n))
    s('something(%s)', n)
  else
    error('something() must be used within a property')

body {
  foo: something(15px) bar;
}
something(n)
  if current-property
    add-property(current-property[0], s('-webkit-something(%s)', n))
    add-property(current-property[0], s('-moz-something(%s)', n))
    s('something(%s)', n)
  else
    error('something() must be used within a property')

body {
  foo: something(15px) bar;
}

生成

body {
  foo: -webkit-something(15px);
  foo: -moz-something(15px);
  foo: something(15px) bar;
}
body {
  foo: -webkit-something(15px);
  foo: -moz-something(15px);
  foo: something(15px) bar;
}

如果您注意到上面的示例,bar 仅存在于初始调用中,因为我们返回了 something(15px),它保留在表达式中,但其他表达式不考虑表达式的其余部分。

我们下面更健壮的解决方案定义了一个名为 replace() 的函数,该函数克隆表达式以防止突变,将表达式的字符串值替换为另一个值,并返回克隆的表达式。然后,我们继续替换表达式中的 __CALL__,它表示对 something() 的循环调用。

replace(expr, str, val)
  expr = clone(expr)
  for e, i in expr
    if str == e
      expr[i] = val
  expr

something(n)
  if current-property
    val = current-property[1]
    webkit = replace(val, '__CALL__', s('-webkit-something(%s)', n))
    moz = replace(val, '__CALL__', s('-moz-something(%s)', n))
    add-property(current-property[0], webkit)
    add-property(current-property[0], moz)
    s('something(%s)', n)
  else
    error('something() must be used within a property')

body
  foo: something(5px) bar baz
replace(expr, str, val)
  expr = clone(expr)
  for e, i in expr
    if str == e
      expr[i] = val
  expr

something(n)
  if current-property
    val = current-property[1]
    webkit = replace(val, '__CALL__', s('-webkit-something(%s)', n))
    moz = replace(val, '__CALL__', s('-moz-something(%s)', n))
    add-property(current-property[0], webkit)
    add-property(current-property[0], moz)
    s('something(%s)', n)
  else
    error('something() must be used within a property')

body
  foo: something(5px) bar baz

生成

body {
  foo: -webkit-something(5px) bar baz;
  foo: -moz-something(5px) bar baz;
  foo: something(5px) bar baz;
}
body {
  foo: -webkit-something(5px) bar baz;
  foo: -moz-something(5px) bar baz;
  foo: something(5px) bar baz;
}

我们的实现现在在它被调用的属性和调用的位置方面都是完全透明的。

这个强大的概念有助于函数调用(例如渐变)的透明供应商支持。

控制台函数

warn(msg)

使用给定的错误 msg 发出警告。不会退出。

warn("oh noes!")
warn("oh noes!")

error(msg)

使用给定的错误 msg 退出 Stylus。

add(a, b)
  unless a is a 'unit' and b is a 'unit'
    error('add() expects units')
  a + b
add(a, b)
  unless a is a 'unit' and b is a 'unit'
    error('add() expects units')
  a + b

p(expr)

检查给定的 expr

fonts = Arial, sans-serif
p('test')
p(123)
p((1 2 3))
p(fonts)
p(#fff)
p(rgba(0,0,0,0.2))

add(a, b)
  a + b

p(add)
fonts = Arial, sans-serif
p('test')
p(123)
p((1 2 3))
p(fonts)
p(#fff)
p(rgba(0,0,0,0.2))

add(a, b)
  a + b

p(add)

stdout

inspect: "test"
inspect: 123
inspect: 1 2 3
inspect: Arial, sans-serif
inspect: #fff
inspect: rgba(0,0,0,0.2)
inspect: add(a, b)
inspect: "test"
inspect: 123
inspect: 1 2 3
inspect: Arial, sans-serif
inspect: #fff
inspect: rgba(0,0,0,0.2)
inspect: add(a, b)

外部文件函数

json(path[, options])

path 中的 JSON 文件转换为 Stylus 变量或对象。嵌套变量对象键使用破折号 (-) 连接。

例如,以下示例 media-queries.json 文件

{
    "small": "screen and (max-width:400px)",
    "tablet": {
        "landscape": "screen and (min-width:600px) and (orientation:landscape)",
        "portrait": "screen and (min-width:600px) and (orientation:portrait)"
    }
}
{
    "small": "screen and (max-width:400px)",
    "tablet": {
        "landscape": "screen and (min-width:600px) and (orientation:landscape)",
        "portrait": "screen and (min-width:600px) and (orientation:portrait)"
    }
}

可以用以下方式使用

json('media-queries.json')

@media small
// => @media screen and (max-width:400px)

@media tablet-landscape
// => @media screen and (min-width:600px) and (orientation:landscape)

vars = json('vars.json', { hash: true })
body
  width: vars.width

vars = json('vars.json', { hash: true, leave-strings: true })
typeof(vars.icon)
// => 'string'

// don't throw an error if the JSON file doesn't exist
optional = json('optional.json', { hash: true, optional: true })
typeof(optional)
// => 'null'
json('media-queries.json')

@media small
// => @media screen and (max-width:400px)

@media tablet-landscape
// => @media screen and (min-width:600px) and (orientation:landscape)

vars = json('vars.json', { hash: true })
body
  width: vars.width

vars = json('vars.json', { hash: true, leave-strings: true })
typeof(vars.icon)
// => 'string'

// don't throw an error if the JSON file doesn't exist
optional = json('optional.json', { hash: true, optional: true })
typeof(optional)
// => 'null'

use(path)

可以使用 use() 函数在 .styl 文件中使用给定 path 中的任何 JS 插件,如下所示

use("plugins/add.js")

width add(10, 100)
// => width: 110
use("plugins/add.js")

width add(10, 100)
// => width: 110

在这种情况下,add.js 插件看起来像这样

var plugin = function(){
  return function(style){
    style.define('add', function(a, b) {
      return a.operate('+', b);
    });
  };
};
module.exports = plugin;
var plugin = function(){
  return function(style){
    style.define('add', function(a, b) {
      return a.operate('+', b);
    });
  };
};
module.exports = plugin;

如果您想返回任何 Stylus 对象,如 RGBAIdentUnit,可以使用提供的 Stylus 节点,如下所示

var plugin = function(){
  return function(style){
    var nodes = this.nodes;
    style.define('something', function() {
      return new nodes.Ident('foobar');
    });
  };
};
module.exports = plugin;
var plugin = function(){
  return function(style){
    var nodes = this.nodes;
    style.define('something', function() {
      return new nodes.Ident('foobar');
    });
  };
};
module.exports = plugin;

可以使用 哈希对象 将任何选项作为可选的第二个参数传递

use("plugins/add.js", { foo: bar })
use("plugins/add.js", { foo: bar })

未定义函数

未定义函数输出为字面量。因此,例如,我们可以在 css 中调用 rgba-stop(50%, #fff),它将按预期输出。我们也可以在助手函数中使用它。

在下面的示例中,我们简单地定义函数 stop(),它返回字面量 rgba-stop() 调用。

stop(pos, rgba)
  rgba-stop(pos, rgba)

stop(50%, orange)
// => rgba-stop(50%, #ffa500)
stop(pos, rgba)
  rgba-stop(pos, rgba)

stop(50%, orange)
// => rgba-stop(50%, #ffa500)