在大多数浏览器中,以下代码将有效。
window.onload = function(){
console.log( document.getElementById('svgElm').getBoundingClientRect().width );
};
这里有一个演示。如果你在Google Chrome中尝试它,控制台将输出200
。然而,FireFox返回0
。
如果无法返回SVG属性,则我最终会回到父级尺寸。这里有一个演示http://jsbin.com/uzoyik/1/edit。
相关代码如下:
svg.clientWidth || svg.parentNode.clientWidth
svg.clientHeight || svg.parentNode.clientHeight
我认为“宽度”不是由getBoundingClientRect方法返回的对象的标准跨浏览器属性。我通常会这样做:
var box = el.getBoundingClientRect();
var width = box.right-box.left;
var height = box.bottom-box.top;
.getComputedStyle()
。由于旧版IE8-浏览器不支持svg
元素,因此.getComputedStyle()
是提供一致结果的方法。所以我最终在我的库中使用了这个函数:var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];
var svgCalculateSize = function (el) {
var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
bounds = {
width: 0,
height: 0
};
heightComponents.forEach(function (css) {
bounds.height += parseFloat(gCS[css]);
});
widthComponents.forEach(function (css) {
bounds.width += parseFloat(gCS[css]);
});
return bounds;
};