svg
요소 의 치수를 얻는 올바른 방법은 무엇입니까 ?
http://jsfiddle.net/langdonx/Xkv3X/
Chrome 28 :
style x
client 300x100
offset 300x100
IE 10 :
stylex
client300x100
offsetundefinedxundefined
FireFox 23 :
"style" "x"
"client" "0x0"
"offset" "undefinedxundefined"
에 너비 및 높이 속성이 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>
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);
CSS
#svg1 {
width: 300px;
height: 100px;
}
답변
getBBox 함수 사용
var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);
답변
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);
답변
Firefox를 사용하고 있으며 작업 솔루션은 obysky에 매우 가깝습니다. 유일한 차이점은 svg 요소에서 호출하는 메서드가 여러 개의 rects를 반환하고 첫 번째 항목을 선택해야한다는 것입니다.
var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;
답변
SVG에는 width
및 height
. SVGAnimatedLength
두 가지 속성이 있는 객체 를 반환합니다 : animVal
및 baseVal
. 이 인터페이스는 애니메이션에 사용됩니다 . 여기서은 애니메이션 이전baseVal
의 값 입니다. 내가 볼 수 있듯이이 방법은 Chrome과 Firefox에서 일관된 값을 반환하므로 계산 된 SVG 크기를 얻는데도 사용할 수 있다고 생각합니다.
답변
이것이 내가 찾은 일관된 브라우저 간 방법입니다.
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;
};
답변
Firefox 33 이후부터는 getBoundingClientRect ()를 호출 할 수 있으며 정상적으로 작동합니다. 즉, 위의 질문에서 300 x 100을 반환합니다.
Firefox 33은 2014 년 10 월 14 일에 출시 될 예정이지만 사용 해보고 싶다면 Firefox nightlies에 이미 수정 사항이 있습니다.
답변
저장 방법 A는 너비 및 높이를 결정하는 수단 어떤 요소 (패딩없이 마진)은 다음이다 :
let div = document.querySelector("div");
let style = getComputedStyle(div);
let width = parseFloat(style.width.replace("px", ""));
let height = parseFloat(style.height.replace("px", ""));