L3F.WIN

Github及Hexo的使用

0%

学习stylus【4】Stylus的方法及函数

方法
stylus 中可以直接定义函数方法,不需要使用 function
下面是一个最简单的返回值的方法

1
2
3
4
5
6
7
add(a, b)
a + b

body
padding add(10px, 5)
=>
body{padding: 15px;}

参数
stylus 中我们可以设置超级参数
例如

1
2
3
4
5
6
7
8
add(a, b = a)
a + b

add(10, 5)
// => 15

add(10)
// => 20

stylus 也可以使用函数作为参数进行调用
例如

1
2
3
4
5
6
7
8
9
10
11
add(a, b = unit(a, px))
a + b

/* unit()为stylus的内置方法,其作用为将参数变为指定单位 */
add(a, b = a)
a = unit(a, px) //将a的单位变为px
b = unit(b, px) //将b的单位变为px
a + b

add(15%, 10deg)
// => 25px

数组
例如

1
2
3
4
5
6
7
8
9
10
11
12
/*#1*/
sizes = 15px 10px

sizes[0]
// => 15px

/*#2*/
sizes()
15px 10px

sizes()[0]
// => 15px

条件判断
我们判断val是否是字符串或缩进。如下,使用yes和no代替true和false.

例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
stringish(val)
if val is a 'string' or val is a 'ident'
yes
else
no

stringish('yay') == yes
// => true

stringish(yay) == yes
// => true

stringish(0) == no
// => true

compare(a, b)
if a > b
higher
else if a < b
lower
else
equal

compare(5, 2)
// => higher

compare(1, 5)
// => lower

compare(10, 10)
// => equal

别名
别名的声明很简单,直接赋值给新的变量即可

1
2
3
4
plus = add

plus(1, 2)
// => 3

函数参数
我们在其他编程语言中也经常遇到,将函数作为参数的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
invoke(a, b, fn)
fn(a, b)

add(a, b)
a + b

body
padding invoke(5, 10, add)
padding invoke(5, 10, sub)

=>
body {
padding: 15;
padding: -5;
}