2015-04-15 57 views
0

我有一個互動式地圖。我正在嘗試創建一個腳本來縮放和平移。只要SVG元素中沒有任何圖像,腳本就會運行。當我將圖像放入其中時,它不再起作用,因爲它選擇圖像並將其拖動。我如何禁用此功能?Jquery pan svg圖像問題

這裏是jQuery代碼:

$(function(){ 
    var mouseX; 
    var mouseY; 
    var originX; 
    var originY; 
    var dX = 0; 
    var dY = 0; 
    var clicking = false; 

    $(document).mousemove(function(e){ 
     mouseX = e.pageX; 
     mouseY = e.pageY; 
    }); 

    $('#P1').on({ 
     mousemove: function(){ 
      if(clicking == true){ 
       dX = originX - mouseX; 
       dY = originY - mouseY; 
      } 
     }, 
     mousedown: function(){ 
      clicking = true; 
      originX = mouseX; 
      originY = mouseY; 
     }, 
     mouseup: function(){ 
      clicking = false; 
      transX = $('#mapSVG').data('transx')+dX; 
      transY = $('#mapSVG').data('transy')+dY; 
      $('#mapSVG').data('transx',transX); 
      $('#mapSVG').data('transy',transY); 
      $('#mapSVG image').attr('transform','translate('+transX+','+transY+')'); 
      $('#mapSVG polygon').attr('transform','translate('+transX+','+transY+')'); 
     } 
    }, '#mapSVG'); 
}); 

這裏是SVG:

<svg id="mapSVG" height="800" width="800" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" data-transx="0" data-transy="0">'; 
    <image x="0" y="0" width="1600px" height="1600px" xlink:href="map.png" transform="translate(0,0"/>'; 
    <polygon points="703,600 704,593 711,588 722,581 739,574 753,571 769,576 771,583 774,586 785,585 790,595 791,607 781,610 780,615 782,624 769,631 751,636 739,640 737,635 721,640 712,633 706,624 704,613 " style="fill:lime; stroke:purple; stroke-width:1; opacity:0.3" transform="translate(0,0)"></polygon> 
</svg>'; 

回答

0

假設正確的SVG將是

<svg id="mapSVG" height="800" width="800" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" data-transx="0" data-transy="0"> 
    <image x="0" y="0" width="1600px" height="1600px" xlink:href="http://upload.wikimedia.org/wikipedia/commons/a/a6/Provinces_of_Sicily_map.png" transform="translate(0,0)"/> 
    <polygon id="P1" points="703,600 704,593 711,588 722,581 739,574 753,571 769,576 771,583 774,586 785,585 790,595 791,607 781,610 780,615 782,624 769,631 751,636 739,640 737,635 721,640 712,633 706,624 704,613 " style="fill:lime; stroke:purple; stroke-width:1; opacity:0.3" transform="translate(0,0)"></polygon> 
</svg> 

具有校正的語法和<polygon> ID爲「P1」(如果我是對的,請相應編輯問題)。

如果#P1不是多邊形,我的答案是無效的。最終我會迭代它。

我做的工作顯然筆,雖然用戶故事是不是100%我清楚:http://codepen.io/pioneerskies/pen/qEegbV在我能看到的唯一問題是一種錯誤的事件委託:您將事件委託給#P1與目標#mapSVG ,但不能將父項事件委派給其子節點之一,因爲委派將「監視」後代中的事件。

關於事件委託的官方jQuery文檔是http://learn.jquery.com/events/event-delegation/