javascript - sass里@if判断语法有什么用?

查看:97
本文介绍了javascript - sass里@if判断语法有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

嵌套循环我都觉得很有用,可是判断有什么用?
判断的使用场景在哪里?为什么会有判断这个语法,为了解决什么问题?

$type: monster;
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}

这是官网给个实例,这样不是很没有意义吗?

直接定义

p {
color: green;
}

不是更加直接吗?
浏览器里没有脚本可以控制sass的type,一切全在sass编译前的环境里运行,编译成css后就只能依靠javascript更改,那么为什么还要@if呢?

解决方案

@小明 说得很对,@if一般是配合@mixin使用的。
@mixin可以用来定义一个样式模板函数。
@if的话,可以在这个函数中作为条件判断。
然后,可以通过@include来调用@mixin

例子的话,可以看这里


补充:

上面的例子已经解释了@if的用法。另外@mixin也可以进行嵌套来减少重复代码。
例如上面的例子的每一个@if里的代码有所重复,可以另外建一个@mixin来处理@if里面的样式。类似这样:

@mixin layout ($color, $unit){
        color: $color;
        font-size: 20px + $unit * 5px;
        height: 20px + $unit * 10px;
        line-height: 20px + $unit * 10px;
        border-radius: $unit * 5px;
}

@mixin title($number, $deg: 90deg, $color1: #69b7eb, $color2: #b3dbd3, $color3: #f4d6db) {
    text-indent: 130px;
    width: 50%;
    background: linear-gradient($deg, $color1, $color2, $color3);
    @if $number == 1 {
        @include layout (#000, $number);
    } @else if $number == 2 {
        @include layout (#444, $number);
    } @else if $number == 3 {
        @include layout (#888, $number);
    } @else if $number == 4 {
        @include layout (#bbb, $number);
    }
}

这篇关于javascript - sass里@if判断语法有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆