zoom on mouse wheel only if ALT key is pressed
I use google map api v3 in my website: the map is width 100% and height 450px. So, when you scroll the page, it will automatically stop on the map because of the mousewheel event to zoom the map. I don't want to disable it because it's kind of a cool feature so I was looking for a way to zoom on mouse wheel only if ALT key is pressed. First, I did it with jQuery like this:
<div id="my_map" class="Scrollable"
onmouseover="hover_div['my_map']=true;" onmouseout="hover_div['my_map']=false;">
"hover_div" is a global array defined in the head, "map" is a global variable (with "scrollwheel" set to false)
$('.Scrollable').on('DOMMouseScroll mousewheel', function(ev) {
if(ev.altKey && hover_div['my_map']){
var $this = $(this),
scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = $this.height(),
delta = (ev.type == 'DOMMouseScroll' ?
ev.originalEvent.detail * -40 :
ev.originalEvent.wheelDelta),
up = delta > 0;
var prevent = function() {
ev.stopPropagation();
ev.preventDefault();
ev.returnValue = false;
return false;
}
if (!up && -delta > scrollHeight - height - scrollTop) {
$this.scrollTop(scrollHeight);
var mapZoom = parseFloat(map.getZoom());
if(mapZoom > 0){
mapZoom = mapZoom - 1;
map.setZoom(mapZoom);
}
return prevent();
} else if (up && delta > scrollTop) {
$this.scrollTop(0);
var mapZoom = parseFloat(map.getZoom());
if(mapZoom < 21){
mapZoom = mapZoom + 1;
map.setZoom(mapZoom);
}
return prevent();
}
}
});
It's working, but it zoom from the center without considering the mouse position as the default event does.
I found this fiddle who trigger the Google Maps mouse wheel event: maybe there's a way to launch the default event only if the ALT key is pressed, but I haven't figured it out yet.
链接地址: http://www.djcxy.com/p/81524.html上一篇: 谷歌地图JS API放大/缩小鼠标滚轮,无需平移地图
下一篇: 只有按下ALT键才能放大鼠标滚轮