SVG 路径鼠标悬停不适用于 Leaflet

SVG path mouseover not working with Leaflet

我遇到了一个问题,即在使用 Leaflet 覆盖窗格时,鼠标悬停事件无法与 SVG path 元素一起使用。我创建了 3 个 SVG 元素(使用 D3.js)——一个 circle、一个 rect 和一个 path。它们都显示正常,鼠标悬停事件在 circlerect 上有效,但在 path 上无效。如果我在没有 Leaflet 的情况下创建相同的 3 个元素,它们都可以正常工作。

这是javascript代码

var mymap = L.map('mapid').setView([51.505, -0.09], 13);

L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(mymap);

//initialize svg to add to map
L.svg({clickable:true}).addTo(mymap)// we have to make the svg layer clickable

const overlay = d3.select(mymap.getPanes().overlayPane)
const svg = overlay.select('svg').attr("pointer-events", "auto")

svg.append('path')
  .attr('d', 'M 110 110 H 190 V 190 H 110 L 110 110')
  .style("fill", "green")
  .attr("stroke", "black")
  .on('mouseover', () => {
      console.log("mouseover path");
      d3.select(event.currentTarget).style("fill", "blue")
  })
  .on('mouseout', () => {
      d3.select(event.currentTarget).style("fill", "green")
  })


svg.append('circle')
  .attr("cx", 300)
  .attr("cy", 200)
  .attr("r", 75)
  .style("fill", "yellow")
  .attr("stroke", "black")
  .on('mouseover', () => {
      console.log("mouseover circle");
      d3.select(event.currentTarget).style("fill", "blue")
  })
  .on('mouseout', () => {
      d3.select(event.currentTarget).style("fill", "yellow")
  })

svg.append('rect')
  .attr("x", 500)
  .attr("y", 200)
  .attr("width", 75)
  .attr("height", 75)
  .style("fill", "red")
  .attr("stroke", "black")
  .on('mouseover', () => {
      console.log("mouseover rect");
      d3.select(event.currentTarget).style("fill", "blue")
  })
  .on('mouseout', () => {
      d3.select(event.currentTarget).style("fill", "red")
  })

这里是 JSFiddle

这是没有 Leaflet 的相同代码 works as I expect

任何人都可以解释为什么鼠标悬停事件不适用于 path 元素吗?谢谢!

如果您在浏览器的调试器中检查路径,您会看到 Leaflet.css 包含此...

.leaflet-marker-icon, .leaflet-marker-shadow, .leaflet-image-layer, .leaflet-pane > svg path, .leaflet-tile-container { pointer-events: none; }

所以它明确地关闭了所有路径的指针事件,这些路径是 SVG 标签的直接后代。

您可以通过添加

来覆盖它
.style("pointer-events", "auto")

到路径生成代码。