我正在尝试将点击处理程序添加到我的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/但似乎在我的情况下不起作用......
答案 0 :(得分:0)
您需要“加载”加载到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() {....} )
});