将onclick事件添加到SVG元素

big*_*man 14 html ajax svg dom

我在SVG教程中找到了这个例子,它解释了如何为svg元素使用onclick事件处理程序.它看起来像下面的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

然而,这似乎不起作用.单击元素时没有任何反应.

也许重要的是要提到我使用echo在php脚本中显示svg的事实.此外,php脚本生成的内容使用AJAX进入页面,并且:

<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>
Run Code Online (Sandbox Code Playgroud)

这可能与它有什么关系吗?非常感谢您的帮助.

mia*_*iah 18

似乎所有的javascript都必须包含在svg中才能运行.我无法引用任何外部函数或库.这意味着你的代码会破坏svgstyle = svgobj.getStyle();

这将做你正在尝试的.

<?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>
Run Code Online (Sandbox Code Playgroud)

  • 有一些方法可以引用外部函数,与从iframe内部调用外部函数的方法相同.这里有一些例子:http://dahlström.net/svg/html/from-svg-to-parent-html-script.html和http://dahlström.net/svg/html/from-svg-get-embedding- element.html. (3认同)

小智 5

JSFiddle中的演示

    var XMAX = 500;
var YMAX = 500;
var _xx=10;
var _reg=100;
var _l=10;
// Create PATH element
for(var x=1;x<20;x++)
{
var pathEl = document.createElementNS("http://www.w3.org/2000/svg", "path");
pathEl.setAttribute('d','M'+_l+' 100 Q 100  300 '+_l+' 500' );
pathEl.style.stroke = 'rgb('+(_reg)+',0,0)';
pathEl.style.strokeWidth = '5';
pathEl.style.fill = 'none';
    $(pathEl).mousemove(function(evt){$(this).css({"strokeWidth":"3","stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#51c000"})});

$('#mySvg').append(pathEl);
_l+=50;
}
Run Code Online (Sandbox Code Playgroud)