简体   繁体   English

结合SVG,HTML和Javascript

[英]Combining SVG, HTML and Javascript

I have an HTML file that looks somehow like this: 我有一个看起来像这样的HTML文件:

<html>
 <div id="test"> ... </div>
 <object data="pic.svg" [...]></object>
</html>

Inside pic.svg, I have an element, let's say, a circle, and I want to realize something like that: 在pic.svg中,我有一个元素,比如说一个圆圈,我想实现这样的功能:

<circle onClick="doSomething()" [...]>

Now, in the js function doSomething() (ie when someone clicks on the circle) I want to change my "test"-div. 现在,在js函数doSomething()中(即当有人单击圆圈时),我想更改我的“ test” -div。 How to do this? 这个怎么做?

If you want the SVG to live in the same DOM as the HTML, best to use an embedded <svg> element. 如果您希望SVG与HTML <svg>在相同的DOM中,则最好使用嵌入式<svg>元素。 It's pretty well supported . 得到很好的支持

Something like 就像是

<svg id="svgroot" width="600" height="600"
     version="1.1" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
<script type="text/ecmascript">//<![CDATA[
   function doSomething() {
       document.getElementById('test').appendChild(...);
   }
//]]></script>

<circle onClick="doSomething()" />
</svg>

You can access the parent document (and consequently the elements there) from inside the svg like this: 您可以从svg内部访问父文档(以及那里的元素),如下所示:

var divInParentDocument = window.parent.document.getElementById('test');

Here's a (slightly more complex) example showing how to call a function in the parent html document from inside an svg. 这是一个(稍微复杂一点)的示例,显示了如何从svg内部调用父html文档中的函数。

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

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