在大多数浏览器中,以下都是可行的。如何在FireFox中获得SVG元素的尺寸?
window.onload = function(){
console.log(document.getElementById('svgElm').getBoundingClientRect().width);
};
这是demo。如果您在谷歌浏览器中试用它,控制台将输出200
。但是,FireFox返回0
。
在大多数浏览器中,以下都是可行的。如何在FireFox中获得SVG元素的尺寸?
window.onload = function(){
console.log(document.getElementById('svgElm').getBoundingClientRect().width);
};
这是demo。如果您在谷歌浏览器中试用它,控制台将输出200
。但是,FireFox返回0
。
如果无法返回SVG属性,我最终会回落到父维度。这里是一个演示http://jsbin.com/uzoyik/1/edit。
的relavent代码是:
svg.clientWidth || svg.parentNode.clientWidth
svg.clientHeight || svg.parentNode.clientHeight
这个Firefox错误是固定在Firefox 33发布于10月14日2014年
见bug 530985了解详情。
我不认为“宽度”是由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;
};
这是一个已知的错误呢? – Gajus