You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SASS如何正确访问多维map嵌套层级的height、width属性

问题原因

你当前的代码漏掉了id维度的取值步骤,也把宽高取值的位置放错了:
map-get($columns, $language) 拿到的是包含1/2/3三个id key的第二层map,不是直接存放宽高的第三层map,你跳过了id匹配的步骤直接取height/width,自然取不到对应值。而且宽高和id是绑定的,你把取值逻辑写在了遍历id的循环外面,此时还没有确定id值,也不可能拿到对应尺寸。

修正后的代码

@for $i from 1 through length($columns) {
    $language: nth(map-keys($columns), $i);
    // 先拿到当前语言对应的所有id尺寸集合
    $langSizeMap: map-get($columns, $language);

    @for $j from 1 through 3 {
        // 匹配当前id,拿到对应宽高map
        $currentSize: map-get($langSizeMap, $j);
        $height: map-get($currentSize, 'height');
        $width: map-get($currentSize, 'width');

        .#{$language} [data-id="#{$j}"] .tile__content {
            background-image: url('images/#{$language}/#{$j}.png');
            height: $height;
            width: $width;
        }
    }
}

更简洁的优化写法

用@each遍历map比@for更灵活,后续新增语言、新增id都不用手动修改循环阈值:

@each $language, $langSizeMap in $columns {
  // 自动遍历当前语言下所有id,不需要写死1到3
  @each $id, $size in $langSizeMap {
    .#{$language} [data-id="#{$id}"] .tile__content {
      background-image: url('images/#{$language}/#{$id}.png');
      height: map-get($size, 'height');
      width: map-get($size, 'width');
    }
  }
}

内容的提问来源于stack exchange,提问作者JackofAll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:06:06