获取svg
元素尺寸的正确方法是什么?
http://jsfiddle.net/langdonx/Xkv3X/
Chrome 28:
style x
client 300x100
offset 300x100
Run Code Online (Sandbox Code Playgroud)
IE 10:
stylex
client300x100
offsetundefinedxundefined
Run Code Online (Sandbox Code Playgroud)
FireFox 23:
"style" "x"
"client" "0x0"
"offset" "undefinedxundefined"
Run Code Online (Sandbox Code Playgroud)
有宽度和高度属性svg1
,但.width.baseVal.value
只有在我设置元素的宽度和高度属性时才设置.
小提琴看起来像这样:
HTML
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="red" />
<circle cx="150" cy="50" r="40" stroke="black" stroke-width="1" fill="green" />
<circle cx="250" cy="50" r="40" stroke="black" stroke-width="1" fill="blue" />
</svg>
Run Code Online (Sandbox Code Playgroud)
JS
var svg1 = document.getElementById('svg1');
console.log(svg1);
console.log('style', svg1.style.width + 'x' + svg1.style.height);
console.log('client', svg1.clientWidth + 'x' + svg1.clientHeight);
console.log('offset', svg1.offsetWidth + 'x' + svg1.offsetHeight);
Run Code Online (Sandbox Code Playgroud)
CSS
#svg1 {
width: 300px;
height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
小智 87
使用getBBox函数
var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);
Run Code Online (Sandbox Code Playgroud)
小智 39
FireFox对getBBox()有疑问,我需要在vanillaJS中执行此操作.
我有一个更好的方法,与真正的svg.getBBox()函数结果相同!
有了这篇好文章:获得SVG/G元素的实际大小
var el = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle
console.log( rect.width );
console.log( rect.height);
Run Code Online (Sandbox Code Playgroud)
SVG有属性width
和height
.它们返回一个SVGAnimatedLength
具有两个属性的对象:animVal
和baseVal
.此接口用于动画,其中baseVal
是动画前的值.从我所看到的,这个方法在Chrome和Firefox中返回一致的值,所以我认为它也可以用于获得SVG的计算大小.
我正在使用Firefox,而我的工作解决方案非常接近obysky.唯一的区别是你在svg元素中调用的方法将返回多个rects,你需要选择第一个.
var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
81919 次 |
最近记录: |