“我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情”
单纯的for循环遍历数字
- 比如有种类型的类,前缀都是一样的,只不过是后面所接的数字不同,这时就能使用循环来创建这些类,避免重复代码
<style lang='scss' scoped>
// 在scss中用#{}来表示变量的值,就像js里用${}来包裹变量一样
$class-prefix: col-;
@for $n from 1 through 24 {
&.#{$class-prefix}#{$n} {
width: ($n/24)*100%;
}
}
</style>
使用@each遍历对象
- 用来处理遍历内容是对象的情况
案例
- 假设有这样的一个重复的响应式代码,大部分结构都一样,只是字符和响应宽度不同。
@media (min-width: 576px) {
$class-prefix: col-ipad-;
@for $n from 1 through 24 {
&.#{$class-prefix}#{$n} {
width: ($n/24)*100%;
}
}
$class-prefix: offset-ipad-;
@for $n from 0 through 24 {
&.#{$class-prefix}#{$n} {
margin-left: ($n/24)*100%;
}
}
}
@media (min-width: 769px) {
$class-prefix: col-narrow-pc-;
@for $n from 1 through 24 {
&.#{$class-prefix}#{$n} {
width: ($n/24)*100%;
}
}
$class-prefix: offset-narrow-pc-;
@for $n from 0 through 24 {
&.#{$class-prefix}#{$n} {
margin-left: ($n/24)*100%;
}
}
}
- 用
@each简化后的代码如下:- 在scss中
#{}的写法就像JS中的${}一样,用来解析变量值 map-get():用来获取对象值,分别传入对象变量和想获取属性的字段
- 在scss中
$widthArr: (
("minWidth":576px, "label":'ipad'),
("minWidth":769px, "label":'narrow-pc'),
);
$prefixArr: (
('label':'col', 'style':width),
('label':'offset-', 'style':margin-left),
);
@each $item in $widthArr {
@media (min-width: #{map-get($item,'minWidth')}) {
@each $prefix in $prefixArr {
$class-prefix: #{map-get($prefix,'label')}-#{map-get($item,'label')}-;
@for $n from 1 through 24 {
&.#{$class-prefix}#{$n} {
#{map-get($prefix,'style')}: ($n/24)*100%;
}
}
}
}
}
虽然有循环嵌套,不过没有了之前长串的重复代码了。😄