svg点击功能不起作用



我试图添加点击处理程序到我的svg。但是函数永远不会触发。

在我的例子中,我替换了svg的路径,因为我不能在这里上传它。但是SVG文件看起来是这样的:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Laag_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 566.9 566.9" style="enable-background:new 0 0 566.9 566.9;" xml:space="preserve">
 <g id="SvgKaart">
    <style type="text/css">
        .st0{fill:none;stroke:#010202;stroke-linejoin:round;stroke-miterlimit:10;}
        .st1{fill:#5EBCA4;stroke:#010202;stroke-linejoin:round;stroke-miterlimit:10;}
        .st2{fill:none;}
        .st3{font-family:'Helvetica';}
        .st4{font-size:29px;}
    </style>
    <polygon class="st0 regio-2 regio" points="133.3,165.3 108.7,124.7 108.7,80.7 121,72 138,58 158,50 176,50 184.7,60 190,70 192.7,78.7
        192.7,95.3 188,104.7 186.7,112.7 184,121.3 180.7,130.7 173.3,139.7 170.7,151.3 164,156.3 153,165.7 146.7,169.3 "/>
    <polygon class="st0 regio-2 regio" points="192.7,78.7 207,78.7 213,66.3 224,64.7 233.3,68.3 245,70 258.3,78.7 259.7,90.3 261.3,95.7 263.3,104
        263.3,148 245,169.3 238.7,171 228,174.3 216.7,178 209,182.3 201,190.3 198.7,197.3 199.3,216.7 176.7,216.7 163.7,221.7
        159.7,224 159.7,197.3 165.7,181.7 169.7,169.3 170.7,151.3 173.3,139.7 180.7,130.7 186.7,112.7 188,104.7 192.7,95.3 "/>
    <polygon class="st0 regio-2 regio" points="133.3,165.3 129.3,173 116.7,182 112.3,185.3 112.3,192.7 115.7,196.3 118.3,203.7 136,225.3
        139.7,227.7 156,227.7 159.7,224 159.7,197.3 169.7,169.3 170.7,151.3 153,165.7 146.7,169.3 "/>
    ...
 </g>
</svg>

这就是我所尝试的:

var svg = Snap('#svgRegioKaart');
Snap.load("path_to_svg", function(f) {
  var layer0 = f.select('g');
  $.each(layer0.selectAll(".regio").items, function() {
    this.click(function() {
      debugger;
      this.attr({
        class: 'st1'
      });
    });
  });
  svg.append(layer0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.4.1/snap.svg-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<svg id="svgRegioKaart" height="567" width="567"></svg>

我找到了这个教程http://www.pixelite.co.nz/article/using-snap-svg-for-rich-interactivity/,但似乎不适合我的情况…

你需要'追加'片段,你加载到DOM,否则你试图添加一个点击处理程序到一些不完全在DOM。

所以在这行之后…

var layer0 = f.select('g'); 

添加
svg.append(layer0); // or svg.append( f ) and remove prev line if you want all the svg loaded

然后从您现在使用Snap添加的svg中选择…

svg.selectAll(".regio").forEach( function() {
    this.click( function() {....} )
});

相关内容

最新更新