请看看这个小提琴:http://jsfiddle.net/arasbm/Tyxea/14/
正如您所看到的,我希望在触发事件时对SVG元素进行转换。您可以单击箭头,它应该工作,因为它使用嵌入在SVG范围内的JavaScript代码:
<svg id="my-svg" width="20cm" height="20cm" viewBox="0 0 600 600"
xmlns="http://www.w3.org/2000/svg" version="1.1">
<desc>Example showing how to transform svg elements
using SVGTransform objects</desc>
<script type="application/ecmascript"> <![CDATA[
function transformMe(evt) {
// svg root element to access the createSVGTransform() function
var svgroot = evt.target.parentNode;
// SVGTransformList of the element that has been clicked on
var tfmList = evt.target.transform.baseVal;
// Create a seperate transform object for each transform
var translate = svgroot.createSVGTransform();
translate.setTranslate(50,5);
var rotate = svgroot.createSVGTransform();
rotate.setRotate(10,0,0);
var scale = svgroot.createSVGTransform();
scale.setScale(0.8,0.8);
// apply the transformations by appending the SVGTranform objects
// to the SVGTransformList associated with the element
tfmList.appendItem(translate);
tfmList.appendItem(rotate);
tfmList.appendItem(scale);
}
]]> </script>
<polygon fill="orange" stroke="black"
stroke-width="5"
points="100,225 100,115 130,115 70,15 70,15 10,115 40,115 40,225"
onclick="transformMe(evt)"/>
...
</svg>
这工作,但我想有我的JavaScript代码从SVG
元素分开。根据这个W3C文档,我应该能够通过使用top
范围引用它来调用javascript函数。这就是我为矩形所做的:
<rect x="200" y="100" width="100" height="100"
fill="yellow" stroke="black" stroke-width="5"
onclick="top.transformMe(evt)"/>
然而,点击矩形会在控制台中出现以下错误:
Error: Permission denied to access property 'transformMe' @ http://fiddle.jshell.net/arasbm/Tyxea/14/show/:1
谁能告诉我如何解决这个问题?我在这个例子中演示的真正问题是:用这些元素之外的JavaScript代码处理SVG元素上的事件的正确方法是什么?fiddle代码中的问题是JSFiddle排列代码的方式。
首先,Javascript在函数体中求值,因此方法transformMe不会成为全局函数。添加
window.transformMe = transformMe
,使函数成为全局的。
然后再次在小提琴代码运行在iframe(也许你的页面是不同的)和"顶部"是指顶部文档,在jsfiddle.net的情况下,你因此试图使跨域JS调用。如果您在打开开发人员工具的情况下运行fiddle,您可以看到这一点:控制台给出正确的提示。
最后但并非最不重要的是,在当前的浏览器实现中,我认为你根本不需要"top"引用。相反,你可以简单地调用全局函数(刚刚在IE, Chrome和FF测试过,它对我有效)。