Html 单击 <svg> 元素上的处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16502015/
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-29 08:18:42  来源:igfitidea点击:

Click handler on <svg> element

javascripthtmlsvgonclickdom-events

提问by jtbandes

It seems that using a <svg:svg> </svg:svg>element does not render anything in Safari or Chrome, but using <svg> </svg>works fine. However, adding an onclickonly works on <svg:svg>elements. What is the proper way to do this?

似乎使用<svg:svg> </svg:svg>元素不会在 Safari 或 Chrome 中呈现任何内容,但使用<svg> </svg>效果很好。但是,添加 anonclick仅适用于<svg:svg>元素。这样做的正确方法是什么?

This jsfiddledemonstrates the problem (compare Safari/Chrome to Firefox).

这个 jsfiddle演示了这个问题(将 Safari/Chrome 与 Firefox 进行比较)。

采纳答案by Malharhak

Okay, turns out that the first way of creating a SVG creates the onclickonly on the drawn part. That means you can actually do something nice (maybe not useful in your case).

好的,事实证明,创建 SVG 的第一种方法是onclick在绘制部分创建唯一的。这意味着您实际上可以做一些不错的事情(在您的情况下可能没有用)。

In this fiddle, I created two separate onclicks, one that triggers when you click specifically the drawing (which i made larger so you can see) and one that triggers when you click on the SVG box, by putting a container around it.

这个小提琴中,我创建了两个单独的onclicks,一个在您专门单击绘图时触发(我将其放大以便您可以看到),另一个在您单击 SVG 框时触发,通过在它周围放置一个容器。

HTML :

HTML :

<div id="svgContainer">
    <svg id="firstSVG" class="s" xmlns="http://www.w3.org/2000/svg">
        <circle cx="50" cy="50" r="25" fill="red"/>
    </svg>
</div>

JS :

JS:

document.getElementById('firstSVG').addEventListener('click', function (event) {
  document.getElementById("output").innerHTML = "Click works here too !";  

}, false);
document.getElementById('svgContainer').addEventListener('click', function (event) {
  document.getElementById("output").innerHTML = "Well, a container seems better.";  

}, true);

So basically just use a container around the SVG, or just use the click on the drawing

所以基本上只是在 SVG 周围使用一个容器,或者只是使用单击绘图

回答by JPSirois

You don't even have to put a container around the SVG.

您甚至不必在 SVG 周围放置容器。

You just need to define a position: relativeto the SVG itself and it solve the click trigger problem.

您只需要为position: relativeSVG 本身定义 a即可解决点击触发问题。

Here's an forked Fiddle showing it: http://jsfiddle.net/jpsirois/xnw1tbL7/

这是一个显示它的分叉小提琴:http: //jsfiddle.net/jpsirois/xnw1tbL7/