我想读取一个SVG文件,确定它的宽度和高度以便进行缩放。目前,我的代码如下所示:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css" media="all">@import "style/style.css";</style>
<meta name="svg.render.forceflash" content="false" />
<script src="svg.js" data-path="svgweb/src/"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"> </script>
<script type="text/javascript">
$(window).load(function() {
function loadContent(){
/* SVG */
var svg = document.getElementById('myimage')
/* Adapt size of SVG */
try {
SVGDoc = svg.contentDocument;
} catch (Err) {
SVGDoc = svg.getSVGDocument;
}
var root = SVGDoc.documentElement;
if (root.attributes['width'] != null) {
var width = root.attributes['width'].nodeValue;
width = width.substring(0, width.length - 2);
width = (width * 1.25);
var height = root.attributes['height'].nodeValue;
height = height.substring(0, height.length - 2);
height = (height * 1.25);
svg.width = width;
svg.height = height;
}
</script>
</head>
<body>
<div id="map">
<!--[if IE]>
<object id="myimage" src="images/myimage.svg" classid="image/svg+xml">
<![endif]-->
<!--[if !IE]>-->
<object id="myimage" data="images/myimage.svg" type="image/svg+xml">
<!--<![endif]-->
</object>
</div>
</body>
</html>
这段代码在Firefox中运行良好(尽管可以看到很短的时间调整大小)。然而,在Chrome中的开发者工具中会出现错误提示:Uncaught TypeError: Cannot read property 'documentElement' of undefined,该错误与“var root = SVGDoc.documentElement;”这一行有关。此外,Chrome不会调整图像大小。
我找不到适用于两个浏览器的有效解决方案。
SVGDocument
继承了Document
接口,该接口具有documentElement
属性。请参见 http://www.w3.org/TR/SVG11/struct.html#InterfaceSVGDocument。 因此,调用documentElement
没有问题。 - Erik DahlströmdocumentElement
,这就是我们首先进入catch
块的原因。回答已更新。 - Frédéric Hamidi