添加onclick事件SVG元素 [英] Add onclick event to SVG element

查看:5374
本文介绍了添加onclick事件SVG元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个例子在SVG教程,解释了如何使用一个onclick事件处理程序的SVG元素。它看起来像下面的code:

I found this example in a SVG tutorial, that explains how you can use an onclick event handler for a svg element. It looks like the code below:

 <svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='600' width='820'>

 <script type="text/ecmascript"><![CDATA[
 function changerect(evt)
 {
 var svgobj=evt.target;
 svgstyle = svgobj.getStyle();
 svgstyle.setProperty ('opacity', 0.3);
 svgobj.setAttribute ('x', 300);
}
]]>
</script>

<rect onclick='changerect(evt)' style='fill:blue;opacity:1' x='10' y='30' width='100'
height='100' />
 </svg>

不过这似乎并没有工作。当我点击的元素上,没有任何反应。

However this doesn't seem to work. Nothing happens when I click on the element.

也许,它提的是,我从一个PHP脚本中显示SVG,利用回声是非常重要的。 此外,通过PHP脚本生成的内容被带入使用AJAX和页面:

Perhaps that it is important to mention the fact that I am displaying the svg from inside a php script, using echo. Also that the content generated by the php script is brought into the page using AJAX and:

 XMLHttpRequest()

难道这也许是有什么关系呢?非常感谢您的帮助。

Could this perhaps have anything to do with it? Thanks a lot for any help.

推荐答案

看来,所有的JavaScript必须包含在SVG里面为它运行。我无法引用任何外部函数,或库。这意味着你的code沃斯打破在 svgstyle = svgobj.getStyle();

It appears that all of the javascript must be included inside of the svg for it to run. I was unable to reference any external function, or libraries. This meant that your code wass breaking at svgstyle = svgobj.getStyle();

这会做你正在尝试的东西。

This will do what you are attempting.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='600' width='820'>

<script type="text/ecmascript"><![CDATA[
    function changerect(evt) {
        var svgobj=evt.target;
        svgobj.style.opacity= 0.3;
        svgobj.setAttribute ('x', 300);
    }
]]>
</script>

<rect onclick='changerect(evt)' style='fill:blue;opacity:1' x='10' y='30' width='100'height='100' />
</svg>

这篇关于添加onclick事件SVG元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆