如何在sass中使用map-deep-get

mil*_*jay 4 css function sass

我正在关注这篇文章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);
}


Run Code Online (Sandbox Code Playgroud)

小智 6

地图深度获取


句法

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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

如何使用:

map-deep-get函数可让您根据需要访问尽可能深的嵌套值,并且也可以用作常规map-get函数。

$exampleMap: (
   "foo": foo,
   "bar": (
      "barfoo": barfoo,
      "barbar": (
         "barbarfoo": barbarfoo,
      ),
   ),
);
Run Code Online (Sandbox Code Playgroud)

Codepen 演示

未嵌套项目:

@debug map-deep-get($exampleMap, "foo") //foo
Run Code Online (Sandbox Code Playgroud)

嵌套项目:

@debug map-deep-get($exampleMap, "bar", "barfoo") //barfoo
Run Code Online (Sandbox Code Playgroud)

嵌套地图:

@debug map-deep-get($exampleMap, "bar", "barbar") //("barbarfoo": barbarfoo)
Run Code Online (Sandbox Code Playgroud)

嵌套嵌套项目:

@debug map-deep-get($exampleMap, "bar", "barbar", "barbarfoo") //barbarfoo
Run Code Online (Sandbox Code Playgroud)