2

SASS 插值语句 #{ }的使用

 2 years ago
source link: https://www.fly63.com/article/detial/11981
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在之前我们已经使用用 / 来进行计算,但如下情况不一样

p{
    font: 16px/30px Arial, Helvetica, sans-serif; 
}

如果需要使用变量,同时又要确保 / 不做除法运算,而是完整地编译到 css 文件中,这种情况怎么办???可以使用 #{} 插值语句将变量包裹。

使用插值语法

p {
    $font-size: 12px;
    $line-height: 30px;
    font: #{$font-size}/#{$line-height} Helvetica,
    sans-serif;
}

通过 #{} 插值语句可以在选择器、属性名、注释中使用变量:

$class-name: danger;
$attr: color;
$author:'老姚';

/* 
   * 这是文件的说明部分
    @author: #{$author}
 */

a.#{$class-name} {
    border-#{$attr}: #F00;
}
/* 
   * 这是文件的说明部分
    @author: 老姚
 */
a.danger {
  border-color: #F00;
}

插值语法说明

插值一般就指插入值在某个位置,该功能不是sass才有的,其实很多语言都有,例如前段的js,如果我们想输出一个带变量的值

var name = '张三',
            age = 20;
console.log('我叫' + name + ',今年' + age + '岁!');

如果有很多变量要输出,或这个串很长的情况是非常麻烦的,所以我们可以用模板字符串输出,像这样

var name = '张三',
            age = 20;
console.log(`我叫${name},今年${age}岁!`);

而sass中的插值用的是#{}把变量包裹起来的,变量可以是几乎任意类型的值;

什么时候会用到插值语法?

注释、选择器、属性名等有变量输出时

上面的安全便是该种情况

$class-name: danger;
$attr: color;
$author:'老姚';

/* 
   * 这是文件的说明部分
    @author: #{$author}
 */

a.#{$class-name} {
    border-#{$attr}: #F00;
}
$themes:( 'light':#f00, 'dark':#000);
@function color($key) {
    @if not map-has-key($themes, $key) {
        @warn " $themes有key里面不包含 `#{$key}`.";
    }
    @return map-get($themes, $key);
}

.container {
    background-color: color('light');
}

更多使用场景欢迎补充

这些情况不能使用插值语法

不可插值用于变量的一部分

$font-size-big: 40px;
$font-size-base: 20px;
$font-size-small: 12px;
$size:big;
.block {
    font-size: $font-size-#{$size}; // Error: Undefined variable.
}

不能在混入里使用

@mixin base {
    margin-top: 20px;
    background: #F00;
}

$flag: "base";
.navigation {
    @include #{$flag}; // Error: Expected identifier.
}

@import后不能使用

$var:'common';
@import #{var};
.block {
    font-size: $font-size;
}

还有更多情况...

插值语法在使用中还是非常方便的,但有些情况不能使用,但不代表后续不能使用,具体情况根据当前使用的版本来,有可能现目前版本不支持的情况,后续版本可能会支持。

来自:https://www.cnblogs.com/top8/archive/2022/08/08/16561712.html

链接: https://www.fly63.com/article/detial/11981


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK