我有一个 SVG,我试图通过使用 jQuery 单击事件将其用作某种导航。
SVG 有几个组,其中有各种路径和文本。当直接单击线条/路径/文本时,事件会被触发,但是当单击透明区域时,尽管仍然是组,但不会触发事件。关于如何定位整个区域有什么建议吗?
示例 fiddle :如果您在方 block 内单击或直接在线条上单击,它将触发,但如果您在方 block 和线条之间单击,则不会触发
https://jsfiddle.net/benhnoou/96q1beu8/2/
jQuery:
$( "#diag-diagnosis" ).click(function() {
alert('diagnosis');
});
SVG 代码:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240.5 200">
<defs>
<style>
.cls-1 {
fill: #fff;
}
.cls-2 {
fill: none;
stroke: #000;
stroke-miterlimit: 10;
stroke-width: 4px;
}
</style>
</defs>
<title>Asset 1</title>
<g id="Layer_2" data-name="Layer 2">
<g id="Layer_1-2" data-name="Layer 1">
<g id="diag-diagnosis">
<g>
<rect class="cls-1" x="0.5" y="0.5" width="201" height="199"/>
<path d="M201,1V199H1V1H201m1-1H0V200H202V0Z"/>
</g>
<line class="cls-2" x1="238.5" y1="16.5" x2="238.5" y2="167.5"/>
</g>
</g>
</g>
</svg>
最佳答案
您可能想查看pointer-events来自 SVG2。 pointer-events
的 bounding-box
属性适用于组和形状。因此这应该使两个对象之间的透明区域可点击。
$("#diag-diagnosis").click(function() {
alert('diagnosis');
});
#diag-diagnosis {
pointer-events: bounding-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240.5 200">
<defs>
<style>
.cls-1 {
fill: #fff;
}
.cls-2 {
fill: none;
stroke: #000;
stroke-miterlimit: 10;
stroke-width: 4px;
}
</style>
</defs>
<title>Asset 1</title>
<g id="Layer_2" data-name="Layer 2">
<g id="Layer_1-2" data-name="Layer 1">
<g id="diag-diagnosis">
<g>
<rect class="cls-1" x="0.5" y="0.5" width="201" height="199"/>
<path d="M201,1V199H1V1H201m1-1H0V200H202V0Z"/>
</g>
<line class="cls-2" x1="238.5" y1="16.5" x2="238.5" y2="167.5"/>
</g>
</g>
</g>
</svg>
关于javascript - jQuery 单击不是在 SVG <g> 上触发,而是在子元素上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57053276/