我有一个 SVG 文档,我希望能够在其中包含一个脚本(使用 <script>
标签)。在此脚本中,我想设置一个函数,该函数将在文档加载并可供操作时调用。
如果我用 HTML 和 JQuery 做这件事,我会使用 $(document).ready(...)
.我希望在 SVG 文档中执行相同的操作,但显然我不能以相同的方式使用 JQuery。
总而言之,我正在寻找的是这样的东西:
测试.svg:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<script type="text/ecmascript" xlink:href="myscript.js" />
<!-- Rest of SVG body goes here -->
</svg>
我的脚本.js:
function init(evt) {
var svgDocument = evt.target.ownerDocument;
var svgRoot = svgDocument.documentElement;
// Manipulate SVG DOM here
}
// --> Somehow attach init() function to onload event of SVG <--
我想尝试在脚本中执行此操作,而不是依赖于明确的 onload="init()"
在 SVG 定义中。 (我想编写一个可以包含在多个 SVG 中的脚本,而无需他们了解脚本的工作原理。)
最佳答案
举个例子
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" onload='init(evt)'>
<script type="text/ecmascript">
function init(evt) {
var svgDocument = evt.target.ownerDocument;
var svgRoot = svgDocument.documentElement;
// Do whatever you like on svgRoot to manipulate your SVG DOM
}
</script>
</svg>
关于javascript - SVG:加载文档后运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7667861/