简体   繁体   English

带外部Javascript文件的SVG和HTML

[英]SVG and HTML with external Javascript file

I have an HTML file named index.html, in which I have included a svg (using the object-tag) and a js-file (using the script-tag). 我有一个名为index.html的HTML文件,其中我包含了一个svg(使用object-tag)和一个js文件(使用script-tag)。 The js functions all work perfectly when called inside the HTML file. 当在HTML文件中调用时,js函数完全可以正常工作。 Now, when I want to access one of my js functions inside the svg-file, I have to link to the js-file in my svg file (using xlink). 现在,当我想访问svg文件中的一个js函数时,我必须链接到我的svg文件中的js文件(使用xlink)。 The functions still work inside the svg file, but as soon as these functions refer to any element in the HTML file (eg document.getElementById('div1')), they don't work anymore (My guess: Probably because the function doesnt look for the element inside the HTML, but inside the SVG-file.) What can I do to make these functions work again? 这些函数仍在svg文件中工作,但只要这些函数引用HTML文件中的任何元素(例如document.getElementById('div1')),它们就不再起作用了(我的猜测:可能是因为函数没有在HTML中查找元素,但在SVG文件中查找。)我可以做些什么才能使这些函数再次起作用?

When you embed a JS function in an SVG, they are always executed in the private scope of the SVG, and thus can not access anything outside of it. 当您在SVG中嵌入JS函数时,它们总是在SVG的私有范围内执行,因此无法访问它之外的任何内容。

When you want to create an interactive web application with dynamic SVGs, you should put the JS functions which modify the SVG in the javascript code of the HTML. 当您想要使用动态SVG创建交互式Web应用程序时,您应该将修改SVG的JS函数放在HTML的javascript代码中。 You can access an SVGs document tree from HTML-embedded javascript by getting the .contentDocument of the <object> element. 您可以通过获取<object>元素的.contentDocument从HTML嵌入式javascript访问SVG文档树。

You can use the top or parent objects to get from the svg to the container html. 您可以使用top或parent对象从svg获取到容器html。 There is a complete svg to container html and container html to svg example with extensive comments here . 有一个完整的svg到容器html和容器html到svg的例子,这里有广泛的评论

In modern browsers, you can simply place the svg directly within the HTML, and JS (and CSS) will work seamlessly on both. 在现代浏览器中,您只需将svg直接放在HTML中,JS(和CSS)就可以在两者上无缝地工作。

<div>
  <svg:svg xmlns:svg="www.w3.org/2000/svg" version="1.1" height="100" width="100" viewBox="0 0 100 100">
    <svg:circle id="circle" cx="50" x="50" y="50"/>
  </svg:svg>
</div>

<script>
    document.getElementById("circle").style.fill="red";
</script>

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

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