【问题标题】:Snap.Svg click function not workingSnap.Svg 点击功能不起作用
【发布时间】:2017-01-12 03:47:43
【问题描述】:

我正在尝试将点击处理程序添加到我的 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/,但它似乎不适用于我的情况...

【问题讨论】:

    标签: javascript html svg snap.svg


    【解决方案1】:

    您需要“附加”加载到 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() {....} )
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多