Javascript 将事件附加到 SVG 路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11701461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:47:01  来源:igfitidea点击:

attach events to SVG paths

javascriptjquerysvg

提问by Gnijuohz

I have a SVG map in my html with the <svg>tag. and I want to attach events so I can click them and trigger some events. I know I can attach click event using jQuery on polygon elements. But some areas in this map are made using paths and I'd like to trigger some events when I click inside the paths, not on the paths.

我的 html 中有一个带有<svg>标签的 SVG 地图。我想附加事件,以便我可以单击它们并触发一些事件。我知道我可以在多边形元素上使用 jQuery 附加点击事件。但是这张地图中的某些区域是使用路径制作的,当我在路径内部而不是在路径上单击时,我想触发一些事件。

What's the way to do that? Using jQuery is preferred.

有什么方法可以做到这一点?最好使用 jQuery。

回答by Phrogz

If you filla <path>then clicking inside it (on the fill) will trigger the event handler:

如果fill一个<path>里面然后单击(在填充)将触发事件处理程序:

Demo: http://jsfiddle.net/TmsrP/1/

演示:http: //jsfiddle.net/TmsrP/1/

<path id="sauce" fill="#f00" … />    
$('#sauce').on('click',function(){ … });

You can choose to explicitly fill the path with the color transparentand mouse events will still be caught:

您可以选择用颜色显式填充路径,transparent鼠标事件仍将被捕获:

Demo: http://jsfiddle.net/TmsrP/2/

演示:http: //jsfiddle.net/TmsrP/2/

<path fill="transparent" … />