简体   繁体   English

如何将事件绑定到svg标签中的元素?

[英]How to bind an event to the element inside svg tag?

I've got an SVG (it's an nvd3 chart). 我有一个SVG(这是nvd3图表)。

Now I need to show a tooltip when the users hovers some text. 现在,当用户悬停一些文本时,我需要显示一个工具提示。

My problem is that even if I manually right-click the "text" tag in Google Chrome and choose "Inspect element", it inspects the SVG container instead of the "text" element. 我的问题是,即使我在Google Chrome浏览器中手动右键单击“文本”标签并选择“检查元素”,它也会检查SVG容器而不是“文本”元素。

But when I click some "rect" tag, everything works like a charm. 但是,当我单击一些“ rect”标签时,所有内容都像一个超级按钮。

So I can do: 所以我可以做:

$('rect').mouseover(sth)

and it works, but I cannot do 它有效,但是我做不到

$('text').mouseover(sth)

because the event is never fired. 因为该事件从未触发过。

When I click the "text" tag, the "click" event is fired on the SVG tag instead of the appropriate one. 当我单击“文本”标记时,将在SVG标记而不是适当的标记上触发“单击”事件。

My SVG Code: 我的SVG代码:

<svg>
    <g class="nvd3 nv-wrap nv-multiBarHorizontalChart" transform="translate(100,0)">
        <g> 
            <g class="nv-x nv-axis">
                <g class="nvd3 nv-wrap nv-axis">
                    <g>
                        <g class="tick major" transform="translate(0,202.26543209876542)" style="opacity: 1;">
                            <text x="-5" dy=".32em" y="0" style="text-anchor: end; display: block;">Android 3.1</text>
                        </g>
                    </g>
                </g>
            </g>        
        </g>
    </g>
</svg>

Fiddle: 小提琴:

http://jsfiddle.net/BChC9/ http://jsfiddle.net/BChC9/

When you click the text, it alerts "text", but in my project, it alerts "svg". 当您单击文本时,它会警告“文本”,但是在我的项目中,它会警告“ svg”。 What could be the cause of it? 可能是什么原因造成的?

If it's only tooltips you need, you could add title elements to the SVG ( try it ): 如果只是您需要的工具提示,则可以将标题元素添加到SVG中( 尝试一下 ):

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="30">
  <text x="10" y="20">
    <title>This is a tooltip</title>
    This is text
  </text>
</svg>

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

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