2014-10-16 116 views
1

我可以让我的对象SVG的JavaScript中的宽度,并保存在一个变量的值。这是我的对象获取宽度或高度SVG矩形的JavaScript

<rect id="cercle1" x="5" y="25" width="50" height="50" stroke-width="1" stroke="#0E0E0E" style="fill:red; stroke:black; stroke-width:2"; /> 

我试试这个:

的document.getElementById( 'cercle1')width.value。

感谢您的帮助

+0

顺便说一句,你可以有'风格=“...”'或演示文稿属性,但你不需要两者都有冲突的值。例如'stroke-width =“1”**或**'style =“stroke-width:2px”'。 – Phrogz 2014-10-16 20:29:54

回答

1

您可以使用getAttribute功能:

document.getElementById('cercle1').getAttribute("width"); 

,将让你从HTML代码字符串。作为提到,您可能希望数字而不是,或实际价值(即可能有所不同)。如果是这样,请参阅his answer

+1

请注意,这将返回一个字符串值。虽然JavaScript是松散类型的,并且在将字符串转换为数字时默默地尝试做正确的事情,但并不总是正确的。你可能想用'+ ...'或'* 1'来转换为实数。 – Phrogz 2014-10-16 17:55:24

+0

@Progro这是真的,这一切都取决于你如何使用它。在某些情况下,这将是足够的,而在其他情况下,您的方法将会更好。 – blex 2014-10-16 18:13:32

1

你可以试试这个:

var obj = document.getElementById("cercle1"); // reference to the object tag 
var rect = obj.getBoundingClientRect(); // get the bounding rectangle 
alert(rect.width); 
alert(rect.height); 

或者这样:

var obj = document.getElementById("cercle1"); // reference to the object tag 
var svgdoc = obj.contentDocument; // reference to the SVG document 
var svgelem = svgdoc.documentElement; // reference to the SVG element 
alert(svgelem.getAttribute("width")); 

这里是一个工作JSFiddle例子。

从从Phrongz注释:请注意,边界矩形将占变换,其可能或可能不期望。

+0

你的第一段代码中的'el'是什么? – blex 2014-10-16 17:47:47

+1

@blex这是一个错字。我修好了它。 – 2014-10-16 17:53:10

+1

注意,边界矩形将占变换,其可能或可能不期望。 – Phrogz 2014-10-16 17:54:34

2

width属性是一个SVGAnimatedLength属性。因此,你需要:

// If you want the original value 
var w = document.getElementById('cercle1').width.baseVal.value; 

// If it is animated and you want the current animated value 
var w = document.getElementById('cercle1').width.animVal.value; 

或者,如果只是想什么是源代码:

var w = document.getElementById('cercle1').getAttribute('width')*1; // convert to num