首页 > 解决方案 > 如何在 sass 中使用 map-deep-get

问题描述

我正在关注这篇文章https://www.sitepoint.com/better-solution-managing-z-index-sass/ 但是缺少一个链接,它没有将 map-deep-get 函数链接回 z功能,并且演示不起作用。我试过搜索但没有找到任何帮助。

$z-layers: (
  "goku":            9001, 
  "shoryuken":       8000,
  "modal": (
    "base":           500,
    "close":          100,
    "header":          50,
    "footer":          10
  ),
  "default":            1,
  "below":             -1,
  "bottomless-pit": -9000
);

@function map-deep-get($map, $keys...) {
  @each $key in $keys {
    $map: map-get($map, $key);
  }

  @return $map;
}

@function z($layer) {
  @if not map-has-key($z-layers, $layer) {
    @warn "No layer found for `#{$layer}` in $z-layers map. Property omitted.";
  }

  @return map-get($z-layers, $layer);
}


标签: cssfunctionsass

解决方案


地图深度获取


句法

Dart Sass syntax:

@use "sass:list";
@use "sass:map";
@use "sass:meta";

@function map-deep-get($map, $keys...) {
   $scope: $map; $i: 1;
   @while (meta.type-of($scope) == map) and ($i <= list.length($keys)) {
      $scope: map.get($scope, list.nth($keys, $i));
      $i: $i + 1;
   }
   @return $scope;
}

Lib Sass syntax:

@function map-deep-get($map, $keys...) {
   $scope: $map; $i: 1;
   @while (type-of($scope) == map) and ($i <= length($keys)) {
      $scope: map-get($scope, nth($keys, $i));
      $i: $i + 1;
   }
   @return $scope;
}

如何使用:

map-deep-get函数让您可以访问任意深度嵌套的值,也可以用作常规map-get函数。

$exampleMap: (
   "foo": foo,
   "bar": (
      "barfoo": barfoo,
      "barbar": (
         "barbarfoo": barbarfoo,
      ),
   ),
);

Codepen Demo

非嵌套项:

@debug map-deep-get($exampleMap, "foo") //foo

嵌套项目:

@debug map-deep-get($exampleMap, "bar", "barfoo") //barfoo

嵌套地图:

@debug map-deep-get($exampleMap, "bar", "barbar") //("barbarfoo": barbarfoo)

嵌套嵌套项:

@debug map-deep-get($exampleMap, "bar", "barbar", "barbarfoo") //barbarfoo

推荐阅读