Sass调用深度map-get取嵌套map值报错map不是合法CSS值如何解决
问题根源
报错的核心原因是get-bg-img函数返回了非合法CSS值(要么是上层嵌套map、要么是null),直接输出到background属性触发校验失败。绝大多数情况是调用mixin时传入的页面key/设备key和$bg-images中定义的key拼写不匹配,且原函数没有做存在性校验,无法提前定位错误。
修复方案
1. 优化取值函数,增加边界校验
给函数增加key存在性判断,拼写错误时直接抛出明确的编译提示,快速定位问题:
@function get-bg-img($map, $keys...) { $current: $map; @each $key in $keys { @if not map-has-key($current, $key) { @error "Key「#{$key}」不存在于当前Sass map中,请检查传入参数的拼写"; } $current: map-get($current, $key); } @return $current; }
2. (可选)优化资源路径存储逻辑,避免url解析异常
将map中的资源路径存为纯字符串,在mixin中再拼接url(),可以规避部分编译工具对嵌套map内url()的解析异常:
// 调整后的map定义 $bg-images: ( home: ( desktop: "../assets/home/background-home-desktop.jpg", tablet: "../assets/home/background-home-tablet.jpg", mobile: "../assets/home/background-home-mobile.jpg" ), destination: ( desktop: "../assets/destination/background-destination-desktop.jpg", tablet: "../assets/destination/background-destination-tablet.jpg", mobile: "../assets/destination/background-destination-mobile.jpg" ), crew: ( desktop: "../assets/crew/background-crew-desktop.jpg", tablet: "../assets/crew/background-crew-tablet.jpg", mobile: "../assets/crew/background-crew-mobile.jpg" ), technology: ( desktop: "../assets/technology/background-technology-desktop.jpg", tablet: "../assets/technology/background-technology-tablet.jpg", mobile: "../assets/technology/background-technology-mobile.jpg" ) ); // 调整后的mixin @mixin background($page, $device) { width: 100%; background: url("#{get-bg-img($bg-images, $page, $device)}"); background-size: cover; }
3. 调用时确保参数和map key完全匹配
注意key的大小写、拼写完全一致,示例调用:
.home-desktop { @include background(home, desktop); }
内容的提问来源于stack exchange,提问作者Tapialj
相关产品推荐
相关产品推荐

