JavaScript 访问 SVG 的内部 DOM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11434916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:12:18  来源:igfitidea点击:

JavaScript accessing inner DOM of SVG

javascriptdomsvg

提问by SomeKittens

test.phpis a SVG object that's being generated with PHP.

test.php是一个用 PHP 生成的 SVG 对象。

<object data="test.php" type="image/svg+xml" id="SVG" />
<script>
    var mySVG = document.getElementById("SVG");
    var svgDoc = mySVG.contentDocument;

svgDocis null. (and so I can't access the elements of the svg via JS.) It should work, looking at this question.What am I doing wrong? How can I get the contentDocumentof my SVG?

svgDoc一片空白。(所以我无法通过 JS 访问 svg 的元素。)它应该可以工作,看看这个问题。我究竟做错了什么?我怎样才能得到contentDocument我的 SVG?

回答by bluetiger9

You need to wait until the SVG is loaded and than you can access the contentDocument:

您需要等到 SVG 加载完毕,然后才能访问 contentDocument:

 var mySVG = document.getElementById("SVG");
 var svgDoc;
 mySVG.addEventListener("load",function() {
      svgDoc = mySVG.contentDocument;
      alert("SVG contentDocument Loaded!");
 }, false);

回答by SomeKittens

Not sure this is an answer, but it worked for me. I had the same problem and svgObjectwas returning null:

不确定这是一个答案,但它对我有用。我遇到了同样的问题,svgObject正在返回null

var svgObject = document.getElementById('svgObject').contentDocument;

var svgObject = document.getElementById('svgObject').contentDocument;

Then it occurred to me that I was running my html page locally: file:///C:/wwwroot/App_dev/OverLay/Overlay03.html

然后我想到我在本地运行我的 html 页面:file:///C:/wwwroot/App_dev/OverLay/Overlay03.html

Running it from the server: http://localhost:62551/App_dev/OverLay/Overlay03.html

从服务器运行它: http://localhost:62551/App_dev/OverLay/Overlay03.html

It worked flawlessly and svgObjectreturned its content, then I could get the divinside it.

它完美地工作并svgObject返回其内容,然后我可以得到div它的内部。