問題描述
在我的頁面上顯示傳單地圖時,我遇到了奇怪的行為.通常地圖會按預期渲染并且運行良好.但是,我只想在我在 javascript 中檢測到的表單中出現錯誤時才顯示地圖.因此,如果我將父 <div id="map">
設置為 display: none;
并稍后根據需要顯示,則不會加載圖塊(或僅部分加載并且不繼續)并且地圖奇怪地錯位"(不是在 js 中定義的居中).
I am experiencing strange behaviour when displaying leaflet map on my page. Normally the map is rendered as expected and works well. However I want to display the map only when an error occurs in forms which I detect in javascript. So if I set the parent <div id="map">
to display: none;
and show it later as needed, the tiles are not loaded (or only partially load and do not continue) and the map is strangely "dislocated" (not centred as defined in js).
我的想法是,也許瀏覽器沒有呈現 display: none;
父級中的元素?
My thought is that maybe the browser does not render the elements inside a display: none;
parent?
我嘗試使用 $(document).ready(...)
函數隱藏地圖,但沒有任何區別.一旦我隱藏并顯示地圖,同樣的行為就會重復.我在 Firefox 44.0 和 Chromium 48.0 上對此進行了測試,行為是一致的.
I tried hiding the map with the $(document).ready(...)
function but it made no difference. The same behaviour repeats as soon as I hide and show the map. I tested this on Firefox 44.0 and Chromium 48.0 and the behaviour is consistent.
任何提示都會有所幫助.這是遠程加載元素 (ajax) 的一般行為嗎?
Any tip would be helpful. Is this general behaviour for remotely loaded elements (ajax)?
現在我知道了解決方案和解決方法(請參閱下面的答案),但我仍然不確定這是否是遠程加載元素的全局行為?感謝您的任何解釋.
Now I know the solution and a workaround (see the answers bellow), but I am still unsure if this is a global behaviour for remotely loaded elements? Thanks for any explanation.
請參閱接受的答案以獲得解釋.
See the accepted answer for explanation.
推薦答案
您的 L.Map
實例由于 display:none而無法正確計算其尺寸代碼> CSS 規則.如果它沒有得到正確的尺寸,它不知道要加載多少瓷磚以及如何布置它們,它只會不加載.XHR 與它無關.地圖不知道 XHR 是什么,這就是問題所在.
What's happening is that your L.Map
instance can not correctly calculate it's dimensions because of the display:none
CSS rule. If it doesn't get the proper dimensions it doesn't know how many tiles to load and how to lay them out, it just loads none. XHR has nothing to do with it. The map doesn't know what to XHR, that's the problem.
從 display:none
切換到 display:block
后,在 L.Map<上調用
invalidateSize
方法/代碼>實例.它將強制地圖(重新)渲染:
After you've switched from display:none
to display:block
call the invalidateSize
method on your L.Map
instance. It will force the map to (re)render:
檢查地圖容器大小是否發生變化,如果發生變化,則更新地圖 - 在您動態更改地圖大小后調用它,默認情況下也會為平移設置動畫.如果 options.pan 為 false,則不會發生平移.如果 options.debounceMoveend 為 true,它會延遲 moveend 事件,這樣即使連續多次調用該方法也不會經常發生.
Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default. If options.pan is false, panning will not occur. If options.debounceMoveend is true, it will delay moveend event so that it doesn't happen often even if the method is called many times in a row.
http://leafletjs.com/reference.html#map-invalidatesize
這篇關于隱藏“顯示:無"時如何渲染傳單地圖父母的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!