如何使用jquery无限扩展svg?

时间:2016-06-03 11:13:13

标签: jquery svg

我正在尝试这个,但它只在第一次点击时有效,而我希望它可以继续缩放各种点击次数:

$(".map").on("click", function(){
   $(".map svg").css({"-moz-transform": "scale(2.0)", "webkit-transform": "scale(2.0)"});
});

2 个答案:

答案 0 :(得分:0)

您需要设置比例值绝对,它不能相对

首次点击后,您的元素已将样式transform设置为scale(2),再次设置相同的样式将不再更改外观。

请查看此代码段,了解它如何工作(使用存储当前比例值的变量)

var zoom_factor = 1;

$(".zoom").click(function(e) {
  // ZOOM IN WITH LEFT MOUSE BUTTON

  zoom_factor *= 1.25;
  
  $(this).css("transform", "scale("+zoom_factor+")");
  return false;
}).bind("contextmenu", function() {
  // ZOOM OUT WITH RIGHT MOUSE BUTTON

  zoom_factor /= 1.25;
  
  $(this).css("transform", "scale("+zoom_factor+")");
  return false;
});
body {
  text-align: center;
}

svg {
  display: inline-block;
  width:100px;
  height:100px;
  
  position: absolute;
  top: 50%;
  margin-top:-50px;
  
  transition:transform .25s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<svg class="zoom" viewBox="0 0 20 20"><path d="M17.684,7.925l-5.131-0.67L10.329,2.57c-0.131-0.275-0.527-0.275-0.658,0L7.447,7.255l-5.131,0.67C2.014,7.964,1.892,8.333,2.113,8.54l3.76,3.568L4.924,17.21c-0.056,0.297,0.261,0.525,0.533,0.379L10,15.109l4.543,2.479c0.273,0.153,0.587-0.089,0.533-0.379l-0.949-5.103l3.76-3.568C18.108,8.333,17.986,7.964,17.684,7.925 M13.481,11.723c-0.089,0.083-0.129,0.205-0.105,0.324l0.848,4.547l-4.047-2.208c-0.055-0.03-0.116-0.045-0.176-0.045s-0.122,0.015-0.176,0.045l-4.047,2.208l0.847-4.547c0.023-0.119-0.016-0.241-0.105-0.324L3.162,8.54L7.74,7.941c0.124-0.016,0.229-0.093,0.282-0.203L10,3.568l1.978,4.17c0.053,0.11,0.158,0.187,0.282,0.203l4.578,0.598L13.481,11.723z"></path></svg>

答案 1 :(得分:0)

因为您仍在添加相同的值:

尝试类似:

HTML:

<div class="map" data-scale="0">
   <svg>...</svg>
</div>

JS:

$(".map").on("click", function(){
    var $map = $(this);
    var $svg = $map.find('svg');
    var current_scale = $map.attr('data-scale');
        current_scale = parseInt(current_scale,10);
    var sclae_to = current_scale + 2;

    $svg.css({'transform': 'scale('+ sclae_to +')'});
    $map.attr('data-scale',sclae_to);
});

演示: https://jsfiddle.net/v0fdpczd/