触发点击SVG图片

时间:2019-02-15 10:11:24

标签: javascript svg

我正在玩SVG图片,以查看是否可以为我的网站创建地图。我从第3方网站上获取了该图像,现在我正试图实施它。这是我所拥有的东西:

https://jsfiddle.net/hL1weg3o/1/

所以 CSS 基本上是:

svg, svg * {
    pointer-events: none;
}
#map {
  display: block;
  text-indent: -9999px;
  width: 100% ;
  height: 600px;
}

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>

    <div id="mapContainer">
        <object id="map" data="https://chambresdhotes.org/2018/franceHigh.svg" type="image/svg+xml"></object>
    </div>


  </body>
</html>

..然后我尝试通过以下方式捕获点击次数:

document.getElementById("FR-A").addEventListener('click', function (event) { test() });

SVG中的路径类似于:

<path id="FR-A" title="Alsace" class="land"
 d="M498.91,208.16L502.37,206.45L501.41,203.92L502.77,202.75L502.05,202.16L503.38,197.19L505.73,195.84L508.91,190.38L508.19,188.16L513.99,177.9L513.19,176.07L510.57,176.47L508.87,175.28L510.21,173.71L509.24,172.42L510.58,167.67L509.44,165.85L511.28,166.21L508.42,164.55L512.58,164.35L514.79,162.8L518.37,156.06L516.75,155.91L515.79,154.05L518.79,149.33L516.06,146.78L516.51,145.88L512.08,144.43L510.96,147.15L508.96,148.25L509.41,146.56L507.87,146.28L507.83,144.51L509.66,143.35L507.81,143.57L507.73,142.59L503.83,141.4L503.38,138.89L504.82,138.9L505.31,137.13L507.05,137.45L508.51,130.56L509.79,129.8L510.96,134.31L517.94,136.33L517.8,137.48L519.26,138.25L524.5,136.67L528.02,138.94L529.75,137.39L532.17,131.3L532.17,131.3L536.13,131.11L536.25,131.93L538.69,130.52L541.69,132.56L544.49,131.02L551.1,135.31L556.89,136.82L553.43,140.7L550.96,147.12L546.08,149.96L545.75,152.17L540.57,157.24L538.95,160.81L539.2,165.15L537.64,166.68L536.15,172.66L536.66,176.85L534.52,178.43L533.41,183.41L529.69,189.69L529.39,195.05L531.58,198.9L528.85,204.64L527.73,210.8L528.49,213.6L526.98,215.84L530.29,221.55L529.95,223.31L526.45,225.53L527.76,226.24L526.39,226.69L526.95,228.06L526.01,229.02L523.64,228.23L523.2,229.14L524.64,229.71L521.77,232.09L519.37,231.53L515.83,232.75L515.37,231.65L512.79,231.37L514.11,228.3L511.23,227.75L511.23,227.75L511.67,226.42L509.3,222.24L505.95,221.67L507.63,217.4L507.24,214.26L503.23,211.3L500.16,210.59z"/>

我误会了您如何捕获div点击?基本上,我需要从单击的路径中获取“ title”的值,然后我的JS才能确定将用户发送到何处。

谢谢!

1 个答案:

答案 0 :(得分:1)

如果要将事件侦听器附加到页面中的形状,则需要将SVG加载到页面的DOM中,否则JS将无法看到它们。

一种方法是将SVG剪切并粘贴到HTML中。另一种方法是通过JS / jQuery将SVG的DOM加载到包装元素(例如DIV)中:

<div id="mapContainer"></div>

<script>
$(function() {
  $('#mapContainer').load("https://chambresdhotes.org/2018/franceHigh.svg", function() {
    $("#FR-A").click(function(event) {
      test();
     });
  });
});
</script>

(对jQuery的致歉;我的JS有点生锈。)

请注意,我在DOM加载块中具有此功能,以确保它仅在加载#mapContainer之后运行。您可以在the Interspan website上看到这一点。将鼠标悬停在左上角的徽标上,而不是单击。原理是相同的,只是使用了悬停事件而不是click事件。