简体   繁体   English

单击处理程序 <svg> 元件

[英]Click handler on <svg> element

It seems that using a <svg:svg> </svg:svg> element does not render anything in Safari or Chrome, but using <svg> </svg> works fine. 似乎使用<svg:svg> </svg:svg>元素在Safari或Chrome中不呈现任何内容,但使用<svg> </svg>工作正常。 However, adding an onclick only works on <svg:svg> elements. 但是,添加onclick仅适用于<svg:svg>元素。 What is the proper way to do this? 这样做的正确方法是什么?

This jsfiddle demonstrates the problem (compare Safari/Chrome to Firefox). 这个jsfiddle演示了这个问题(比较Safari / Chrome和Firefox)。

You don't even have to put a container around the SVG. 您甚至不必在SVG周围放置容器。

You just need to define a position: relative to the SVG itself and it solve the click trigger problem. 您只需要定义一个position: relative对于SVG本身,它解决了点击触发问题。

Here's an forked Fiddle showing it: http://jsfiddle.net/jpsirois/xnw1tbL7/ 这是一个分叉的小提琴显示它: http//jsfiddle.net/jpsirois/xnw1tbL7/

Okay, turns out that the first way of creating a SVG creates the onclick only on the drawn part. 好的,事实证明,创建SVG的第一种方法是仅在绘制的部分上创建onclick That means you can actually do something nice (maybe not useful in your case). 这意味着你可以做一些不错的事情(在你的情况下可能没用)。

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. 这个小提琴中 ,我创建了两个单独的onclick s,一个在你专门点击绘图时触发(一个我做得更大,你可以看到),一个在你点击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周围使用一个容器,或者只是使用图纸上的点击

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM