如何在svg上检测鼠标事件?

如何在svg上检测鼠标事件?,svg,Svg,我的地图看起来像: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="rootMap" version="1.2" baseProfile="tiny" zoomAndPan="disable" viewBox="0 0 327 273"> <style> path, rect{fill: #fff;stroke: #000;cursor:

我的地图看起来像:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="rootMap" version="1.2" baseProfile="tiny" zoomAndPan="disable" viewBox="0 0 327 273">
<style>
    path, rect{fill: #fff;stroke: #000;cursor: crosshair;}      
</style>
<script>
    function test(evt){
        alert(evt.target.id);
    }
</script>   
<svg x="0" y="0" onclick="test(evt)" width="327" height="273" viewBox="596302 -1188413 45 38">
    <g>
        <g>
            <g>
                <rect x="596302" y="-1188413" width="30" height="30" id="2"/>
            </g>
        </g>
    </g>
</svg>
<svg x="0" y="0" onclick="test(evt)" width="327" height="273" viewBox="50000 -600000 327 273">
    <g>
        <g>
            <g>
                <rect x="50000" y="-600000" width="100" height="50" id="1"/>
            </g>
        </g>
    </g>
</svg>

路径,rect{fill:#fff;笔划:#000;光标:十字线;}
功能测试(evt){
警报(evt.target.id);
}

我希望在单击任何rect时,都会调用函数测试。但是当单击rect#1为真时,没有调用rect#2。为什么?

在您的示例中,rect#1位于rect#2之上。当单击两个或多个元素重叠的点时,onclick处理程序只针对最顶层的元素调用。这是有意义的,因为最上面的元素覆盖(即隐藏)了其他元素