container-collapse
本文回答:首屏黑屏 / 地图不出现 —— 容器
<div>尺寸为 0 或定位缺失。
一、症状
- 页面里留了
<div id="map">但看不到地图 - Console 没报错
- Elements 面板看 canvas 大小是 0×0
- 或者有 canvas 但
<div>尺寸正常,map.resize 后好了
二、根因排查
1 容器没尺寸
<div id="map"></div>
默认 <div> 没有高度 → canvas 0×0 → 画面空。
修法:
<div id="map" style="width: 100%; height: 600px; position: relative;"></div>
或在 CSS:
#map { width: 100%; height: 100vh; position: relative; }
2 父元素没设高度
<div id="parent">
<div id="map" style="width: 100%; height: 100%;"></div>
</div>
子 100% 要求父有具体高度;#parent 如果没高度 → #map 是 0。
修法:
html, body, #parent { height: 100%; margin: 0; }
#map { width: 100%; height: 100%; position: relative; }
3 position 缺失
vjmap 内部插入 canvas 时依赖容器 position: relative / absolute。
#map { position: relative; } /* 必须 */
4 display: none 时初始化
new vjmap.Map({ container: 'map' });
// 容器此时 display: none → canvas 尺寸 0
// 等容器显示后:
map.resize();
必须在容器 display 正确时才能正确初始化;否则 display 变化后调 map.resize()。
5 父容器 flex / grid 导致子元素塌陷
<div style="display: flex;">
<div id="map" style="flex: 1;"></div> <!-- 高度 auto,内容为空 → 0 -->
</div>
修法:
<div style="display: flex; height: 100vh;">
<div id="map" style="flex: 1; position: relative;"></div>
</div>
父设 height: 100vh;或 align-items: stretch(flex 默认值)+ 父高度。
三、调试技巧
// 初始化后检查
const el = document.getElementById('map');
console.log('container size:', el.offsetWidth, el.offsetHeight);
// 应该 > 0
// 打开 DevTools Elements 面板
// 1. 选中 #map
// 2. 看 Computed → width / height
// 3. 0 → 回去检查 CSS
四、容器尺寸变化
容器大小变化(用户拖 panel)→ map 不会自动 resize:
const ro = new ResizeObserver(() => map.resize());
ro.observe(document.getElementById('map'));
卸载:
ro.disconnect();
五、Vue 3 容器 ref
<template>
<div ref="mapEl" class="map"></div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const mapEl = ref(null);
let map;
onMounted(() => {
// 容器已挂载
map = new vjmap.Map({ container: mapEl.value });
});
</script>
<style scoped>
.map { width: 100%; height: 600px; position: relative; }
</style>
六、隐藏 tab 里打开地图
// tab 切换前
tab.addEventListener('shown', () => {
if (!map) {
map = new vjmap.Map({ container: 'map' });
} else {
map.resize();
}
});
display: none 下初始化会有问题;展示后 resize 即可。
七、常见坑
height: 100%无效:父级没设高度;从 html/body 开始往下传。- 100vh 在移动端不准:地址栏遮挡;用
height: 100dvh,并监听visualViewport的 resize 调map.resize()。 - iframe 里用:iframe 本身要有尺寸。
- CSS 动画后不显示:transition 过程中 canvas 位置计算错;transition 结束后 resize。
- Grid 布局里
fr子项没高:grid template rows 必须定死或1fr。
相关
- 容器配置 → setup/container
- Vue / React 集成 → setup/integrations