Sass控制指令

发布时间 2023-12-27 22:31:10作者: Ewar-k

@if

sass中的条件控制指令用法同JavaScript中的if语句用法大致一样。例如:

$cond:14px;
body{
	@if $cond < 0px{
		@error 'this is availavle';
	}@else if $cond > 100px{
		@warn 'the value is too large';
	}@else{
		margin-top:$cond;
	}
}

@for

@for 指令可以在限制的范围内重复输出格式,每次按要求(变量的值)对输出结果做出变动。
它有两种写法:

  • @for $var from <start> through <end> : 条件范围包含 的值
  • @for $var from <start> to <end> : 条件范围只包含 的值不包含 的值

$var 可以是任何变量;<start><end> 必须是整数值。

代码实例:

@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}

编译结果:

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

@each

@each可以用来遍历一个值列表【例如:a,b,c或(12,23,34)】
指令的格式是 $var in <list>, $var 可以是任何变量名,比如 $length 或者 $name,而 <list> 是一连串的值,也就是值列表。

基本用法

@each $animal in puma, sea-slug, egret, salamander {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
  }
}

编译结果:

.puma-icon {
  background-image: url('/images/puma.png'); }
.sea-slug-icon {
  background-image: url('/images/sea-slug.png'); }
.egret-icon {
  background-image: url('/images/egret.png'); }
.salamander-icon {
  background-image: url('/images/salamander.png'); }

高级用法一: 同时遍历多个列表

@each $className,$width,$color in (h1,h2),(12px,10px),(blue,red){
    .#{$className}-icon{
    	width:$width;
        color:$color;
	}
}

编译结果:

.h1-icon{
    width:12px;
    color:blue;
}
.h2-icon{
    width:10px;
    color:red;
}

高级用法二: 遍历拉列表的key和value

@each $name,$color in (h1:blue,h2:red){
    .#{$name}-icon{
        color:$color;
	}
}

编译结果:

.h1-icon{
	color:blue;
}

.h2-icon{
	color:red;
}

@while

@while 指令重复输出格式直到表达式返回结果为 false。类似于JavaScript中的while语句。

$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}
.item-6 {
  width: 12em; }

.item-4 {
  width: 8em; }

.item-2 {
  width: 4em; }