L3F.WIN

Github及Hexo的使用

0%

学习stylus【3】

使用运算符号
和其他语言一样 stylus 也有运算符号,
最常用的 + - * / % 等等
逻辑运算符号 !, ==, !=, >=, >, <=, <等等
stylus 中都可以使用。而且 stylus 提供很多新的运算符号。

看下面的例子,这里面基本将所有的运算符号使用了一遍,大家可以参考使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
margin 15px + 5px  => margin: 20px; /*加*/
margin 15px - 5px => margin: 10px; /*减*/
margin 15px * 5px => margin: 75px; /*乘*/
margin 15px / 5px => margin: 3px; /*除*/
margin 15 % 5px => margin: 0px; /*求余*/
!15px => false /*否定*/
!!15px => true /*双否定*/
15px == 15px => true /*并且*/
15px and 14px => false /*并且*/
2 ** 8 => 256 /*指数*/
10px > 5px => true /*判断*/
2 && 3 => 3
0 || 2 => 2
0 && 2 => 0

Mixins混入
感觉混入和函数的定义是一样的,但用处不同。Mixins混入作为状态调用,而非表达调用
我们使用官网的一条例子可以来学习一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
border-radius(n)
-webkit-border-radius n
-moz-border-radius n
border-radius n

form input[type=button]
border-radius(5px)

=>
form input[type=button] {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}

使用Mixins混入可以省略括号。
经常被使用的还有透明的处理,以下代码可以用作参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
support-for-ie ?= true

opacity(n)
opacity n
if support-for-ie
filter unquote('progid:DXImageTransform.Microsoft.Alpha(Opacity=' + round(n * 100) + ')')

#logo
&:hover
opacity 0.5
=>
#logo:hover {
opacity: 0.5;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50);
}

父级引用
Mixins混入可以使用字符&引用父级,

例如要用stripe(even, odd)创建一个条纹表格。even和odd均提供了默认颜色值,每行也指定了background-color属性。我们可以在tr嵌套中使用&来引用tr,以提供even颜色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
stripe(even = #fff, odd = #eee)
tr
background-color odd
&.even
&:nth-child(even)
background-color even
然后,利用混合书写,如下:

table
stripe()
td
padding 4px 10px

table#users
stripe(#303030, #494848)
td
color white

另外,stripe()的定义无需父引用:

stripe(even = #fff, odd = #eee)
  tr
    background-color odd
  tr.even
  tr:nth-child(even)
    background-color even

如果你愿意,你可以把stripe()当作属性调用。

stripe #fff #000
Mixins混入中使用Mixins混入
自然,Mixins混入可以利用其它Mixins混入,建立在它们自己的属性和选择器上。

例如,下面我们创建内联comma-list()(通过inline-list())以及逗号分隔的无序列表。

inline-list()
  li
    display inline

comma-list()
  inline-list()
  li
    &:after
      content ', '
    &:last-child:after
      content ''

ul
  comma-list()
渲染:

ul li:after {
  content: ", ";
}
ul li:last-child:after {
  content: "";
}
ul li {
  display: inline;
}