关联数组 SCSS/SASS

39

我需要将数字转换为单词:

  • "1-3" -> "one-third"
  • "3-3" -> "three-thirds"
  • "2-5" -> "two-fifths"

这些数字是在循环中生成的,应该输出一堆不同的类名,如one-thirdone-half

$number = 3;

@for $i from 1 through $number-1 {
    // some calculations to output those classes: ".one-third", ".two-thirds"

    // The following currently outputs class names like ".1-3" and ".2-3"
    .#{$i}-#{$number} {
        // CSS styles
    }
}

我认为我需要使用两个不同的关联数组,在 PHP 中(仅举例)可能如下所示:

$1 = array( 
   "1"=>"one", 
   "2"=>"two", 
   "3"=>"three" 
);

$2 = array( 
   "1"=>"whole", 
   "2"=>"half", 
   "3"=>"third" 
);

SASS/SCSS中是否有可能创建关联数组,或者是否有任何解决方法?


2
即将推出的 Sass 版本 - v3.3 - 引入了 Maps,可以像关联数组一样使用:https://github.com/nex3/sass/blob/master/doc-src/SASS_CHANGELOG.md#sassscript-maps - KatieK
2个回答

67

在 Sass < 3.3 版本中,您可以使用多维列表:

$numbers: (3 "three") (4 "four");

@each $i in $numbers {
    .#{nth($i,2)}-#{nth($i,1)} {
        /* CSS styles */
    }
}

演示

Sass >= 3.3 版本引入了地图(Maps):

$numbers: ("3": "three", "4": "four");

@each $number, $i in $numbers {
    .#{$i}-#{$number} {
        /* CSS styles */
    }
}

因此,在分数方面,您可以沿着这个方向做一些事情,这样您就不需要多个列表或映射:

DEMO


$number: 6;
$name: (
    ("one"),
    ("two" "halv" "halves"),
    ("three" "third" "thirds"),
    ("four" "quarter" "quarters"),
    ("five" "fifth" "fifths"),
    ("six" "sixth" "sixsths")
);

然后你可以做任何你想要做的循环操作...甚至可能像这样 =D

@for $i from 1 to $number {
  @for $j from 2 through $number {
    .#{ nth( nth( $name, $i ), 1 ) }-#{
      if( $i>1,
        nth( nth( $name, $j ), 3 ),
        nth( nth( $name, $j ), 2 )
      )} {
        /* CSS styles */
    }
  }
}

演示

(我这样写是为了让你注意到在@for中,使用to会循环到n-1)


1
谢谢,这很好用。直到现在我才知道多维列表的存在。一开始我不确定为什么你使用了两次nth,但是测试后我发现你必须这样做,因为列表显然是多维的。 - mrksbnch

11

除了Martin的答案之外,我还有一个例子可以使用颜色作为变量,并且也适用于像 darken() 这样的颜色处理函数:

$blue: rgb(50, 57, 178);
$green: rgb(209, 229, 100);
$orange: rgb(255, 189, 29);
$purple: rgb(144, 19, 254);

$colors: (
        "blue": $blue,
        "green": $green,
        "orange": $orange,
        "purple": $purple
);

@each $name, $color in $colors {
  .tc-#{$name} { color: #{$color} !important; }
  .bgc-#{$name} { background-color: #{$color} !important; }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接