SASS 插值语句 #{ }的使用
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.
在之前我们已经使用用 / 来进行计算,但如下情况不一样
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
Recommend
-
50
-
34
-
58
作者:Erica Sadun, 原文链接 ,原文日期:2018-12-12 译者: RocZhang ;校对:...
-
36
-
58
作者:Olivier Halligon, 原文链接 ,原文日期:2018-12-15 译者:
-
34
作者:Olivier Halligon, 原文链接 ,原文日期:2018-12-16 译者: Nemocdz ;...
-
33
查找--插值查找(Java) 博客说明 文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢! 介绍 插值查找算法类似于二分查找,不同的是插...
-
27
线性插值 已知中P1点和P2点,坐标分别为(x1, y1)、(x2, y2),要计算 [x1, x2] 区间内某一位置 x 在直线上的y值: 根据初中的几...
-
10
Android属性动画详解(二),插值器和估值器
-
6
在不使用cv2等库的情况下利用numpy实现双线性插值缩放图像 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK