2010-09-28 74 views

回答

1

使用CTRLALT,或SHIFT很可能是有问题的,因为这些键是由浏览器用来表示各种动作。不过,我想下面的例子中,结合中号键,以便在按下拖:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps - Drag Marker while Key is Pressed</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script> 
</head> 
<body> 
    <div id="map" style="width: 400px; height: 300px;"></div> 

    <script type="text/javascript"> 

    var map = new google.maps.Map(document.getElementById('map'), { 
    mapTypeId: google.maps.MapTypeId.TERRAIN 
    }); 
    var markerBounds = new google.maps.LatLngBounds(); 
    var markers = []; 
    var i; 

    var createKeyHandler = function (type, keycode) { 
    return (function (e) { 
     var keyPress; 

     if (typeof event !== 'undefined') { 
     keyPress = event.keyCode; 
     } 
     else if (e) { 
     keyPress = e.which; 
     } 

     if (keyPress === keycode) { 
     for (i = 0; i < markers.length; i++) { 
      // while key is down, all markers are set to draggable = true 
      if (type === 'down') { 
      markers[i].setDraggable(true); 
      } 
      else { 
      markers[i].setDraggable(false); 
      } 
     } 
     } 

     return false; // Prevents the default action 
    }); 
    }; 

    // Add 10 random markers on the map 
    for (i = 0; i < 10; i++) { 
    markers.push(new google.maps.Marker({ 
     map: map, 
     draggable: false, 
     position: new google.maps.LatLng(39.00 + (Math.random() - 0.5) * 20, 
             -77.00 + (Math.random() - 0.5) * 20) 
    })); 

    markerBounds.extend(markers[markers.length - 1].getPosition()); 
    } 

    // Adjust the map viewport to fit all the markers 
    map.fitBounds(markerBounds); 

    // Add event handlers for keydown and keyup 
    document.onkeydown = createKeyHandler('down', 77); 
    document.onkeyup = createKeyHandler('up', 77); 

    </script> 
</body> 
</html> 

测试在Firefox 3.6的Mac。但在Chrome上似乎并不能很顺畅地工作,但我会乐观地努力使其工作。

相关问题