如何访问外部加载的svg文件的ID? [英] How to access id's of externally loaded svg file?
问题描述
我发现,如果将svg嵌入到html中,那么我可以简单地访问ID:
I find that if I embed svg in my html then I can access the id's simply:
<svg width="100" height="100">
<circle id='myCircle' cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
JavaScript:
Javascript:
$('#myCircle').css('fill','red'); //效果很好
$('#myCircle').css('fill','red'); // works fine
但是,如果我从外部加载此svg文件:
But if I load this svg file externally:
<object id='myfile' data="myfile.svg" type="image/svg+xml">
</object>
(并假设此svg包含与上述相同的ID/内容) 我做不到:
(and assuming this svg contains the same id/content as above) I cannot do:
$('#myCircle').css('fill','red'); // doesn't work anymore
所以我想知道如何访问外部加载的.svg文件的ID?
so I'm wondering how I can access the id's of externally loaded .svg files?
更新:
我尝试过
var doc = $('#piano')[0] .contentDocument; doc.getElementById('#myCircle);
var doc = $('#piano')[0].contentDocument; doc.getElementById('#myCircle);
但是我明白了,(我正在使用Chrome)
But I get, (I'm using Chrome)
SecurityError:无法从"HTMLObjectElement"读取"contentDocument"属性:阻止了具有"null"原点的框架访问跨域框架.
SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "null" from accessing a cross-origin frame.
推荐答案
如果您希望DOM访问svg,最好的方法是为HTML5文档内联加载svg文件,即创建DIV id ="svgDiv" ,并使用svgDiv.innerHTML接受XMLHttpRequest.responseText
If you want DOM access to your svg, the best way is to load svg files inline for your HTML5 document, is to create a DIV id="svgDiv", and use svgDiv.innerHTML to accept XMLHttpRequest.responseText
下面是一个示例:
function loadSVGInline()
{
var SVGFile="mySVG.svg"
var loadXML = new XMLHttpRequest;
function handler(){
if(loadXML.readyState == 4 && loadXML.status == 200)
{
svgDiv.innerHTML=loadXML.responseText
}
}
if (loadXML != null){
loadXML.open("GET", SVGFile, true);
loadXML.onreadystatechange = handler;
loadXML.send();
}
}
这篇关于如何访问外部加载的svg文件的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!