函数
自定义函数
要实现函数的声明和返回内容我们需要使用function和return两个指令,类似于其他语言中的关键字。
@function 函数名(形参) {
@return;
}
使用时时直接使用 函数名即可
@function getWidth($w) {
@return $w * 2;
}
.main{
max-width: #{getWidth(20)}px;
}
编译后
.main {
max-width: 40px;
}
内置函数
内置函数是指语言本身针对一些数据类型和结构的常用操作进行封装,方便使用。
Sass函数api链接
这里只会针对列表与Map的常见操作进行整理,其他更加详细的内容需要读者自己进行查阅了,官方API已经整理的很好啦
这些是对列表和Map都可以使用的函数
length($list) // 返回列表或者Map的长度.
nth($list, $n) // 返回列表或者Map中的一个元素,$n在是元素对应的index从1开始.
set-nth($list, $n, $value) // 替换列表或者Map中的元素.
join($list1, $list2, [$separator, $bracketed]) // 将两个列表或者Maps合并.
append($list1, $val, [$separator]) // 讲一个元素添加至列表或者Map中
zip($lists…) //将多个列表或者Map合并成新的列表或者Map里面每一个元素是原来单个列表
index($list, $value) // 返回列表或Map中元素的index
list-separator($list) // 返回list的分割符号有comma 逗号 space 空格
is-bracketed($list) // 返回一个列表或者map是否被()包裹
$arr : 1 2 3 4;
$map : ("a":1,"b":2);
这里面的list元素为1、2、3、4,map中的元素为 "a" 1 、 "b" 2。没有错在map中元素就是 key value。kee与value都可以为null,list里也是可以存在null,不过null是不会编译到css中的
接下来针对map还有一些常见内置函数
map-get($map, $key) //根据key返回value
map-merge($map1, $map2) //将两个map合并为一个map
map-remove($map, $keys…) //根据key移除value
map-keys($map) //返回map中所有的key
map-values($map) //返回map中所有的values
map-has-key($map, $key)//判断map中是否存在key
type-of($value) //返回一个数值的数据类型
总结
- 指令就是告诉计算机从事某一特殊运算的代码。
- 自定义函数需要使用到@function内置指令
- Sass函数api链接
scss定义两套主题变量实例:
///////////////////////////////////自定义全局变量
// 浅色主题
$light-theme: (
border-color: #eceeef,
font-color:#323232,
font-secondary: #c2c6d0,
background-color:#fff,
bg-title:#d3e6fb,
bg-oddList:#f3f3f3,
bg-listHover:#c5dffe
);
//深色主题
$dark-theme: (
border-color: #000,
font-color:#c2c6d0,
font-secondary: #aaa,
background-color:#131925,
bg-title:#293248,
bg-oddList:#171e2c,
bg-listHover:#0d3a70
);
//定义映射集合
$themes: (
light: $light-theme,
dark: $dark-theme
);
@mixin themify($themes: $themes) {
@each $theme-name, $map in $themes {
.theme-#{$theme-name} & {
$theme-map: () !global;
@each $key, $value in $map {
$theme-map: map-merge($theme-map, ($key: $value)) !global;
}
@content;
$theme-map: null !global;
}
}
}
@function themed($key) {
@return map-get($theme-map, $key);
}
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@include themify($themes) {
background: themed('background-color');
color:themed('font-color');
}
}
编译为css:
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.theme-light #app {
background: #fff;
color: #323232;
}
.theme-dark #app {
background: #131925;
color: #c2c6d0;
}
网友评论