[英]Get width or height svg rectangle javascript
我可以在javascript中獲取對象svg的寬度並將值保存在變量中。 這是我的目標
<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;
感謝幫助
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
你可以試試這個:
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的評論:請注意,邊界矩形將考慮變換,這可能是也可能不是。
如果您已動態創建了rect,則以下解決方案有效
var rect = document.createElementNS(svgns, "rect");
rect.setAttribute('width', '200px');
rect.setAttribute('height', '200px');
var width= rect.width.baseVal.value;
var height= rect.width.baseVal.value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.