6

我正在尝试创建一个函数,它使我能够在 CSS 中输出简单二维映射的键名键值:

$people: (
    "Hellen": (
        age: "34",
        sex: "female"
    ),
    "Patrick": (
        age: "23",
        sex: "male"
    ),
    "George": (
        age: "10",
        sex: "male"
    ),
    "Vicky": (
        age: "19",
        sex: "female"
    )
);

我正在创建一个简单的函数来检索这些信息:

@each $person-name, $person-details in $people {
    $age: map-get($person-details, 'age');
    $sex: map-get($person-details, 'sex');

    .#{$person-name} {

        height: 100 px;
        width: 100 px;
        background: #FF3C00;
        margin: 0 auto;

        &:before {
            content:$person-name " " + $age " ";
        }

        &:after {
            content: $sex;
        }

    }

}

HTML:

<div class="Hellen"></div>

但是我找不到任何将键和值作为单独对象的信息。我只能读取值,而不是具有以下内容的键:

$age: map-get($person-details, 'age');

结果:

Hellen 34 female

而不是:Hellen 年龄:34 性别:女性

如何获取带有或不带有值的键标签?

4

1 回答 1

14

用于map-keys()获取列表中的所有键。

样本:

@each $person-name, $person-details in $people {
    $age: map-get($person-details, 'age');
    $sex: map-get($person-details, 'sex');
    $keys: map-keys($person-details);

    .#{$person-name} {

        height: 100 px;
        width: 100 px;
        background: #FF3C00;
        margin: 0 auto;

        &:before {
            content:"#{$person-name}  #{nth($keys, 1)} : #{$age} ";
        }

        &:after {
            content: "#{nth($keys, 2)}: #{$sex}";
        }

    }

}
于 2016-06-13T14:37:06.277 回答