单击< svg>上的处理程序元件 [英] Click handler on <svg> element
问题描述
似乎使用< svg:svg> < / svg:svg>
元素在Safari或Chrome中不呈现任何内容,但使用< svg> < / svg>
工作正常。但是,添加 onclick
仅适用于< svg:svg>
元素。这样做的正确方法是什么?
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 onclick
only works on <svg:svg>
elements. What is the proper way to do this?
这个jsfiddle 演示了问题(将Safari / Chrome与Firefox进行比较)。
This jsfiddle demonstrates the problem (compare Safari/Chrome to Firefox).
推荐答案
好的,原来是第一种方式创建SVG仅在绘制的部分上创建 onclick
。这意味着你实际上可以做一些不错的事情(在你的情况下可能没用)。
Okay, turns out that the first way of creating a SVG creates the onclick
only on the drawn part. That means you can actually do something nice (maybe not useful in your case).
在这个小提琴,我创建了两个单独的 onclick
s,当你专门点击绘图时我会触发它(我做了更大的你可以看到)和点击SVG框时触发的一个,在它周围放一个容器。
In this fiddle, I created two separate onclick
s, 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.
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:
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);
所以基本上只是在SVG周围使用一个容器,或者只是使用图纸上的点击
So basically just use a container around the SVG, or just use the click on the drawing
这篇关于单击< svg>上的处理程序元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!