因为习惯太久的黑暗,所以阳光愈加刺眼!

空一座旧城,守一个旧人

4.sass的分支结构、循环结构、函数

分支结构

在sass里,可以使用@if让我们根据一些条件来应用特定的样式

结构:

@if 条件 {
    
}

如果条件为真的话,括号里的代码就会释放出来

例如:

$use-refixes:true;
.rounded{
   @if $use-refixes {
   	-webkit-border-radius:5px;
   	-moz-border-radius:5px;
   	-ms-border-radius:5px;
   	-o-border-radius:5px;
   }
   border-radius:5px;
}

--->

.rounded {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -ms-border-radius: 5px;
  -o-border-radius: 5px;
  border-radius: 5px;
}

如果是另外一种情况

$use-refixes:false;

---》

.rounded {
  border-radius: 5px;
}

if else在sass里的写法是:

body{
	@if $theme == dark {
		background:black;
	} @else if $theme == light {
		background:white;
	} @else {
		background:gray;
	}
}

for循环

在sass里的for循环是这样的

@for $var form <开始值> through <结束值> {
    ...
}

还有一种是

@for $var form <开始值> to <结束值> {
    ...
}

注意,开始值和结束值的关系可以是升序也可以是倒序,但是每次只能+1或者-1

这两种有什么区别呢?

区别就是 from 1 to 4 的话是执行三次,i的变化是 1 2 3

from 1 through 4 的话是执行四次,i的变化是 1 2 3 4

如:

from to

$columns:4;
@for $i from 1 to $columns{
	.col-#{$i}{
		width:100% / $columns * $i;
	}
}

---》

.col-1 {
  width: 25%;
}

.col-2 {
  width: 50%;
}

.col-3 {
  width: 75%;
}

from through

$columns:4;
@for $i from 1 through $columns{
	.col-#{$i}{
		width:100% / $columns * $i;
	}
}

--->

.col-1 {
  width: 25%;
}

.col-2 {
  width: 50%;
}

.col-3 {
  width: 75%;
}

.col-4 {
  width: 100%;
}

each 遍历list类型

在sass里可以利用each方法来遍历咱们的list类型的数据

list类型在js里类似于数组,那么each类似于for in遍历,结构如下:

@each $item in $list{
    ...
}

例如:

$colors:success error warning;
$map:(success:green,warning:yellow,error:red);
@each $color in $colors{
	.bg-#{$color}{
		background:map-get($map,$color);
	}
}

--->

.bg-success {
  background: green;
}

.bg-error {
  background: red;
}

.bg-warning {
  background: yellow;
}

@while 循环

在sass里,拥有@while循环,比@for会更好用一些,@for循环只能从一个数到另一个数变化之间执行,每次变化都是1,while设置循环结构的话更为灵活;

结构:

@while 条件{
    
}

eq:

$i:6;

@while $i>0{
	.item-#{$i}{
		width:$i*5px;
	}
	$i:$i - 2;
}

注意:$i - 2 需要用空格隔开哟

---------》

.item-6 {
  width: 30px;
}

.item-4 {
  width: 20px;
}

.item-2 {
  width: 10px;
}

自定义函数

在sass里也可以定义函数,并且也可以有返回值

结构:

@function 名称 (参数1,参数2){
    @return ...
}

例如,我们做一个返回map里key对应的值的函数:

$colors:(light:#ffffff,dark:#000000,gray:#555555);

@function color($key){
	@return map-get($colors,$key);
}

body{
	background:color(light);
	color:color(dark);
	border-color:color(gray);
}

---》

body {
  background: #ffffff;
  color: #000000;
  border-color: #555555;
}

posted on 2017-12-08 10:07  空一座旧城,守一个旧人  阅读(400)  评论(0编辑  收藏  举报

导航