最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Click handler on <svg> element - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Oct 5, 2019 at 12:17 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked May 11, 2013 at 21:44 jtbandesjtbandes 119k38 gold badges240 silver badges279 bronze badges 2
  • 1 Why you don't use jquery to handle the events.It's easier? – Ionel Lupu Commented May 11, 2013 at 21:52
  • Actually it works on both. But in chrome it only works if you click on the red dot. – user568109 Commented May 11, 2013 at 22:03
Add a comment  | 

2 Answers 2

Reset to default 8

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/

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

发布评论

评论列表(0)

  1. 暂无评论