我将circle.svg加载到svg的组中并想要访问圈子的元素(减号或svgbar)。 circle.svg中的任何内容都会显示为null或未定义。
我尝试将其作为对象加载,但它甚至无法加载图像。 我尝试搜索contentDocument,但是contentDocument未定义。
任何帮助将不胜感激。
circle.svg的内容:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg id="minus" xmlns="http://www.w3.org/2000/svg" width="32px" height="32px" >
<circle id="svgbar" cx="16" cy="16" r="16" />
<rect id="iline" x="8" y="14" fill="#F9F9F9" width="16" height="4" />
</svg>
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>How to access externally loaded svg elements</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
var vis = d3.select( "body" ).append( "svg" ).attr( "id", "svgObj" );
var grp = vis.append( "g" ).attr( "id", "grp" );
/*var img = grp.append( "object" )
.attr( "type", "image/svg+xml" )
.attr( "data", "imgs/nav/circle.svg" );*/
var img = grp.append( "image" )
.attr( "id", "collapse" )
.attr( "xlink:href", "imgs/nav/circle.svg" );
img.attr( "height", 20 )
.attr( "width", 20 )
.on( "mouseover", function() {
console.log( "overing..." );
} );
var befSvgObj = document.getElementById('svgObj');
console.log( "befSvgObj: " + befSvgObj );
// wait until all the resources are loaded
window.addEventListener( "load", findSVGElements, false);
function findSVGElements() {
var contDoc = befSvgObj.contentDocument;
var svgObj = document.getElementById('svgObj');
var gObj = document.getElementById( 'grp' );
var cObj = document.getElementById( 'collapse' );
var svgBar = document.getElementById( 'svgBar' );
var minus = document.getElementById('minus'); // null
//var minus2 = cObj.contentDocument.getElementById( 'minus' );
// Cannot call method 'getElementById' of undefined
console.log( "svgObj: " + svgObj );
console.log( "gObj: " + gObj );
console.log( "cObj: " + cObj );
console.log( "minus: " + minus );
console.log( "svgObj.contentDocument: " + svgObj.contentDocument );
console.log( "gObj.contentDocument: " + gObj.contentDocument );
console.log( "cObj.contentDocument: " + cObj.contentDocument );
console.log( "contDoc: " + contDoc );
console.log( "svgBar: " + svgBar );
}
</script>
</body>
</html>
取值
答案 0 :(得分:2)
如果您将外部SVG作为图像嵌入,那就是您所获得的 - 图像,您不能再修改它而不是PNG或JPEG图像。 Read the W3 specs for more.
如果您需要访问或修改外部SVG的内容,this answer describes how to read the external file as XML and insert it in your current document。