SVGSVGElement: viewBox 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

SVGSVGElement 介面的只讀屬性 viewBoxSVGAnimatedRect 物件的形式反映了 SVGSVGElement 元素的 <svg> 屬性的 viewBox

該屬性描述了 <svg> 元素的 viewBox 屬性,該屬性用於定義 <svg> 元素的 x 座標、y 座標、寬度和高度。SVGAnimatedRect.baseValSVGAnimatedRect.animVal 屬性都是 SVGRect 物件,如果 viewBox 未定義,則為 null。這些物件的元件可能與 SVGSVGElement.xSVGSVGElement.ySVGSVGElement.widthSVGSVGElement.height 屬性不同,因為 xywidthheight 屬性會覆蓋 viewBox 屬性。

對於非巢狀的 SVG 元素,CSS xywidthheight 屬性的值會覆蓋任何元素屬性,因此由 viewBox 定義的值可能不會反映在元素的顯示中。

一個 SVGAnimatedRect 物件。

示例

給出以下 SVG 開頭標籤

html
<svg viewBox="-12 -18 200 300" x="5" y="5" height="400" width="600"></svg>

我們可以檢索 viewBox 的值,但它們與 xywidthheight 屬性不同

js
const svg = document.querySelector("svg");
const vBox = svg.viewBox;

// The SVGSVGElement viewBox property
console.dir(vBox); // SVGAnimatedRect { baseVal: SVGRect, animVal: SVGRect }
console.log(vBox.baseVal.x); // -12
console.log(vBox.baseVal.y); // -18
console.log(vBox.baseVal.width); // 200
console.log(vBox.baseVal.height); // 300

// Other SVGSVGElement properties
console.log(svg.x); // 5
console.log(svg.y); // 5
console.log(svg.width); // 400
console.log(svg.height); // 600

規範

規範
Scalable Vector Graphics (SVG) 2
# __svg__SVGFitToViewBox__viewBox

瀏覽器相容性

另見