SVGTextContentElement: getSubStringLength() 方法

Baseline 已廣泛支援

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

SVGTextContentElement 介面的 getSubStringLength() 方法表示元素內文字子字串的格式化文字前進距離的計算長度。

請注意,此方法僅考慮子字串中字形的寬度以及 CSS letter-spacingword-spacing 屬性插入的額外間距。由 x 屬性進行的視覺間距調整將被忽略。

語法

js
getSubStringLength(index, length)

引數

index

一個 integer;子字串的起始索引。

length

一個 integer;要包含在子字串中的字元數。

返回值

浮點數。

異常

IndexSizeError DOMException

如果 index 大於最高索引或 length 為負數,則丟擲此異常。

示例

獲取子字串的長度

html
<svg width="300" height="100">
  <text id="exampleText" x="10" y="50" font-size="16">Hello, SVG World!</text>
</svg>
js
const textElement = document.getElementById("exampleText");

// Get the length of a substring starting at character 0 with 5 characters
const substringLength = textElement.getSubStringLength(0, 5);

console.log(substringLength); // Output: 35.55

規範

規範
Scalable Vector Graphics (SVG) 2
# __svg__SVGTextContentElement__getSubStringLength

瀏覽器相容性