Sass学习之路(12)——控制命令

来源:互联网 发布:南风知我意七微书包网 编辑:程序博客网 时间:2024/04/28 10:34

Sass的控制命令其实和JS以及其他一些语言中的非常相似:

1.@if

@if指令是一个SassScript,可以根据条件来处理样式块,在条件为true或false时,会返回不同的样式块。它也可以配合@else if 以及@else一起使用。

下边是一个通过@if来控制元素显示隐藏的例子:

//SCSS@mixin blockOrHidden($boolean:true) {  @if $boolean {      display: block;    }  @else {      display: none;    }}.block {  @include blockOrHidden;}.hidden{  @include blockOrHidden(false);}
编译出来的CSS:

.block {  display: block;}.hidden {  display: none;}


2.@for循环

这里依然和其他变成语言中的for循环大同小异,在Sass中,循环有下面两种写法:

@for $i from <start> through <end>@for $i from <start> to <end>
$i表示变量,start为起始值,end为结束值。两种写法在于,使用through表示包括end,使用to表示不包括。也就是小于等于和小于的区别。

我们先来看一个使用through的例子:

@for $i from 1 through 3 {  .item-#{$i} { width: 2em * $i; }}
编译结果如下:

.item-1 {  width: 2em;}.item-2 {  width: 4em;}.item-3 {  width: 6em;}

再来一个to的例子:

@for $i from 1 to 3 {  .item-#{$i} { width: 2em * $i; }}
编译结果如下:

.item-1 {  width: 2em;}.item-2 {  width: 4em;}


3.@while循环

@while循环会在表达式值为false之前,不停地循环执行,生成不同的样式块。这个和for循环也是非常相似的。例如:

//SCSS$types: 4;$type-width: 20px;@while $types > 0 {    .while-#{$types} {        width: $type-width + $types;    }    $types: $types - 1;}
编译结果如下:

.while-4 {  width: 24px;}.while-3 {  width: 23px;}.while-2 {  width: 22px;}.while-1 {  width: 21px;}


4.@each循环

@each循环一般用来遍历一个列表,然后从列表中取出对应的value或key。

@each的写法如下:

@each $var in <list>

这里是一个同过@each遍历列表内容并循环给不同代码块赋予对应的图片背景的例子:

$list: adam john wynn mason kuroir;//$list 这里是一个列表@mixin author-images {    @each $author in $list {        .photo-#{$author} {            background: url("/images/avatars/#{$author}.png") no-repeat;        }    }}.author-bio {    @include author-images;}
最终编译出来的CSS如下:
.author-bio .photo-adam {  background: url("/images/avatars/adam.png") no-repeat; }.author-bio .photo-john {  background: url("/images/avatars/john.png") no-repeat; }.author-bio .photo-wynn {  background: url("/images/avatars/wynn.png") no-repeat; }.author-bio .photo-mason {  background: url("/images/avatars/mason.png") no-repeat; }.author-bio .photo-kuroir {  background: url("/images/avatars/kuroir.png") no-repeat; }

好的,对于Sass中的控制指令就写到这里啦

欢迎小伙伴们一起来讨论关于编程的各种内容~







2 0