【问题标题】:Associative Array SCSS/SASS关联阵列 SCSS/SASS
【发布时间】:2014-02-16 04:02:32
【问题描述】:

我需要将数字转换成单词,所以:

  • “1-3”->“三分之一”
  • “3-3”->“三分之三”
  • “2-5”->“五分之二”

数字是在循环中生成的,它应该输出一堆不同的类名,如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 中创建关联数组,或者是否有任何解决方法?

【问题讨论】:

标签: arrays sass


【解决方案1】:

除了 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; }
}

【讨论】:

    【解决方案2】:

    在 Sass

    $numbers: (3 "three") (4 "four");
    
    @each $i in $numbers {
        .#{nth($i,2)}-#{nth($i,1)} {
            /* CSS styles */
        }
    }
    

    DEMO

    在 Sass >= 3.3 中,我们得到地图:

    $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 */
        }
      }
    }
    

    DEMO

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

    【讨论】:

    • 谢谢,效果很好。直到现在才知道多维列表。我不知道你为什么用了 nth 两次,但经过测试,我发现你必须这样做,因为列表显然是多维的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2018-12-17
    • 1970-01-01
    • 2011-01-15
    • 2017-10-02
    相关资源
    最近更新 更多