How to access id's of externally loaded svg fi

2019-05-23 21:17发布

This question already has an answer here:

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:

$('#myCircle').css('fill','red'); // works fine

But if I load this svg file externally:

<object id='myfile' data="myfile.svg" type="image/svg+xml">
</object>

(and assuming this svg contains the same id/content as above) I cannot do:

$('#myCircle').css('fill','red'); // doesn't work anymore

so I'm wondering how I can access the id's of externally loaded .svg files?

Update:

I tried

var doc = $('#piano')[0].contentDocument; doc.getElementById('#myCircle);

But I get, (I'm using Chrome)

SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "null" from accessing a cross-origin frame.

2条回答
Fickle 薄情
2楼-- · 2019-05-23 21:36

Unfortunately, unlike the iframe element, when you reference your SVG from another file, it's not loaded as a document you can manipulate.

查看更多
来,给爷笑一个
3楼-- · 2019-05-23 21:45

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

Below is an example:

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();
    }
}
查看更多
登录 后发表回答