簡體   English   中英

獲取寬度或高度svg矩形javascript

[英]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;

感謝幫助

您可以使用getAttribute函數:

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

這將從HTML代碼中獲取字符串。 正如Phrogz提到的那樣,你可能想要一個數字,或者實際值(可能是不同的)。 如果是這樣,請參考他的回答

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM