今天我花了一些时间试图用D3(和jQuery)来操纵SVG.我的目标是能够通过JavaScript访问/修改本地SVG.如果它是针对D3量身定制的那么无关紧要,但那将是额外的积分.
似乎适用于其他人的解决方案对我不起作用,它具有以下JavaScript:
window.onload=function() {
// Get the Object by ID
var a = document.getElementById("svgObject");
// Get the SVG document inside the Object tag
var svgDoc = a.contentDocument;
// Get one of the SVG items by ID;
var svgItem = svgDoc.getElementById("svgItem");
// Set the colour to something else
svgItem.setAttribute("fill", "lime");
};
Run Code Online (Sandbox Code Playgroud)
用这个HTML object
<object id="svgObject" data="img/svgfile.svg" type="image/svg+xml" height="50" width="50"></object>
Run Code Online (Sandbox Code Playgroud)
和单独的SVG文件
<svg height="40px" width="40px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800">
<rect id="svgItem" width="800" height="800" fill="red"></rect>
<circle cx="400" cy="400" r="400" fill="blue"></circle>
</svg> …Run Code Online (Sandbox Code Playgroud)