Click handler on <svg> element

跟風遠走 提交于 2019-12-07 03:48:12

问题


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?

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


回答1:


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).

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.

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);

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




回答2:


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

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

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



来源:https://stackoverflow.com/questions/16502015/click-handler-on-svg-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!