2011-11-29 256 views
0

我正在使用Google Maps API將地圖上的一系列點拉回來。我也拉回了ID =「directionsPanel」元素中顯示的方向。除了事實上,當我們超過一定數量的點(Firefox中的3個,Chrome中的4個)時,這一切都很好,它們溢出了頁面。動態高度jQuery

我使用以下jQuery代碼,以檢測元件的高度是什麼(方向被加載之後大概),然後相應地調整它:

$(document).ready(function() { 
    if($.browser.mozilla) 
    { 
    var sHeight = $("#directionsPanel").height(); 
    sHeight = (sHeight * 1.5); 
    $("#directionsPanel").height(sHeight); 
    } 
    else 
    { 
    // do stuff for other browsers 
    } 

}); 

不幸的是,元件不被調整到適量(也許它沒有檢測到正確的初始高度?),事情仍然在頁面上溢出。有關我如何使這更健壯的任何想法?

+0

我會試試這個在螢火蟲控制檯。也許'$(document).ready()'發生在方向被加載之前? – Muhd

+0

我認爲Google Maps API可能會讓您指定地圖加載時的回調函數,這就是您應該放置代碼的地方。 – Muhd

+0

@Muhd:這將是完美的,我會研究回調方法。謝謝! –

回答

1

Google Maps API可能允許您指定地圖加載時的回調函數,並且這是您應該放置代碼的位置。

例如:

var directionsDisplay; 
var directionsService = new google.maps.DirectionsService(); 
var map; 
var haight = new google.maps.LatLng(37.7699298, -122.4469157); 
var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205); 

function initialize() { 
    directionsDisplay = new google.maps.DirectionsRenderer(); 
    var myOptions = { 
    zoom: 14, 
    mapTypeId: google.maps.MapTypeId.ROADMAP, 
    center: haight 
    } 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    directionsDisplay.setMap(map); 
} 

function calcRoute() { 
    var selectedMode = document.getElementById("mode").value; 
    var request = { 
     origin: haight, 
     destination: oceanBeach, 
     // Note that Javascript allows us to access the constant 
     // using square brackets and a string value as its 
     // "property." 
     travelMode: google.maps.TravelMode[selectedMode] 
    }; 
    directionsService.route(request, function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
     directionsDisplay.setDirections(response); 
    } 
    //YOUR CODE FOR RESIZING HERE 
    }); 
} 
<div> 
<b>Mode of Travel: </b> 
<select id="mode" onchange="calcRoute();"> 
    <option value="DRIVING">Driving</option> 
    <option value="WALKING">Walking</option> 
    <option value="BICYCLING">Bicycling</option> 
</select> 
</div> 

不要使用$(document).ready(),因爲加載的DOM時,立即執行。

+0

應該注意的是'$(window).load()'應該可以解決他的問題,但是如果可用的話,使用地圖回調就是更好的方法。 –