跳至內容

內建函式

色彩函式

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])

傳回路徑的基礎名稱,(選擇性地)移除副檔名。

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(path)

傳回路徑的目錄名稱。

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

extname(path)

傳回路徑的副檔名,包含句點。

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'

清單 / Hash 函數

push(expr, 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...)

將指定的參數前置至 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(list, value)

傳回 value 在 list 中的(以 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)

傳回指定 pairs 中的鍵。

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)

傳回指定 pairs 中的值。

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(list)

傳回指定 list 的分隔符號。

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(node)

傳回 node 的類型為字串。

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(angle)

傳回給定 angle 的正弦值。如果角度以度數單位給出,例如 45deg,則將其視為度數,否則將其視為弧度。

sin(30deg)
// => 0.5

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

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

cos(angle)

傳回給定 angle 的餘弦值。如果角度以度數單位給出,例如 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(單位)

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

sum(數字)

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

avg(數字)

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

range(開始, 結束[, 步驟])

傳回從 開始結束 (包含) 的單位清單,以指定的 步驟 遞增。

如果省略 步驟 參數,預設為 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(數字, 基底, 寬度)

傳回轉換為提供的 基底字面值 數字,並以 寬度 個零填充。

寬度預設為 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(樣式, 字串[, 旗標])

傳回 字串樣式 (正規表示式) 的任何比對結果。

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(樣式, 替換, 值)

傳回字串 ,在將所有 樣式 比對結果替換為 替換 之後。

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

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

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

join(分隔符號, 值...)

使用 分隔符號 連接指定的

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(分隔符號, 值)

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(值, 開始, 長度)

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 檔案中使用任何 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)