[英]How to get the embedding element from inside an svg
Using mySVGNode.parentNode I get null for an embedded svg file. 使用mySVGNode.parentNode,对于嵌入式svg文件,我会得到null。 Ideally I want to reference the embed tag and its id attribute.
理想情况下,我想引用embed标签及其id属性。
I can successfully search the DOM for it, but I am surprised parentNode returns null. 我可以为它成功搜索DOM,但是我很惊讶parentNode返回null。 Is it not supported for embedded objects?
嵌入式对象不支持它吗?
What you're looking for is window.frameElement
. 您正在寻找的是
window.frameElement
。 See the definition in the html5 spec . 请参阅html5规范中的定义。
window.frameElement
is the way to go, as @Eric said, but it unfortunately doesn't work in IE or Edge. 正如@Eric所说,
window.frameElement
是要走的路,但是不幸的是,它在IE或Edge中不起作用。
There is a workaround, however, which is to get the parent document, find the <object>
or <embed>
tags in it (which may reference your SVG), and, for each of them, check whether the contentDocument
is our SVG document. 但是,有一种解决方法,即获取父文档,在其中找到
<object>
或<embed>
标签(它们可能引用您的SVG),然后针对每个标签检查contentDocument
是否为我们的SVG文档。
Unlike regular DOM searching by ID, this avoids the need to assign a unique ID for you object/embed tag. 与按ID进行常规DOM搜索不同,这避免了为对象/嵌入标签分配唯一ID的需要。
Example: 例:
var objectElt = window.frameElement;
if (!objectElt) { // IE/Edge case
var objectElts = window.parent.document.getElementsByTagName("object");
for (var i = 0; i < objectElts.length; i++) {
if (objectElts[i].contentDocument == document) {
objectElt = objectElts[i];
break;
}
}
}
// objectElt now references the appropriate <object> tag
您可以使用window.parent.document访问嵌入文档,以便通过其id获取embed标签,您可以执行以下操作...
window.parent.document.getElementById("<whatever your embed Id attribute is>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.