使用css和jquery放大效果

时间:2013-10-17 13:46:52

标签: jquery css

我为我正在作为宠物项目工作的浏览器游戏创建了一个开销地图。

我有一个固定大小的视口div和一个内部div,里面有我所有的地图图标元素。我正在使用jquery-ui来使内部div可拖动,但我也希望能够用鼠标滚轮给它一个缩放效果。

我做了一些谷歌搜索,但似乎没有任何好的解决方案。

我试过了:

$('#map').bind('DOMMouseScroll mousewheel', function(e){
  if(e.originalEvent.wheelDelta /120 > 0) {
    $("#map").css("width", "+=10");
  }
  else{
    $("#map").css("width", "-=10");
  }
});

但它没有做任何事情,所以我想我并没有约束正确的事件。 (是的,我正在文档中运行该jquery代码(准备好了))

1 个答案:

答案 0 :(得分:0)

想出来。这是后代的代码:

$('#map').bind('mousewheel DOMMouseScroll', function(e){
  //Get the transformation matrix from the css as a string. (it's named differently for different browsers)
  var scale = $(this).css('transform');
  scale = (scale == null ? $(this).css('-webkit-transform') : scale); 
  scale = (scale == null ? $(this).css('-ms-transform') : scale);
  //once we have the matrix, the scale is the first number, so parse the string to remove it.
  scale = scale.split(" ");
  scale = parseFloat(scale[0].substring(7, scale[0].length - 1));

  //e.originalEvent tells us how the mousewheel moves. (Also different for different systems)
  e.delta = null;
  if (e.originalEvent) {
    if (e.originalEvent.wheelDelta) e.delta = e.originalEvent.wheelDelta / -40;
    if (e.originalEvent.deltaY) e.delta = e.originalEvent.deltaY;
    if (e.originalEvent.detail) e.delta = e.originalEvent.detail;
  }
  //If delta is greater than 0, we're zooming in
  if(e.delta > 0) { 
    //5x zoom is the max that I want to zoom in.
    if(scale < 5) {
      //no need to re-form the matrix. specifying a new scale value will do the job.
      scale = ('scale(' + (scale + .1).toString() + ')');
      //update the transform css for each possible browser. 
      $(this).css({'transform':scale, '-ms-transform':scale, '-webkit-transform':scale });
    }
  }
  //if delta is less than zero, we're zooming out
  else{
    //for my purposes, I don't want to zoom out farther than the original map size
    if(scale > 1) {
      scale = ('scale(' + (scale - .1).toString() + ')');
      $(this).css({'transform':scale, '-ms-transform':scale, '-webkit-transform':scale });
    }
  }