SVGLengthList

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

SVGLengthList 接口定义了一个 SVGLength 对象列表。它用于 SVGAnimatedLengthListbaseValanimVal 属性。

SVGLengthList 对象可以被指定为只读,这意味着尝试修改该对象将导致抛出异常。

SVGLengthList 对象是可索引的,可以像数组一样访问。

实例属性

length

列表中项目的数量。

numberOfItems

列表中项目的数量。

实例方法

appendItem()

在列表末尾插入一个新项。

clear()

清除列表中的所有现有项,结果将是一个空列表。

initialize()

清除列表中的所有现有项,并将列表重新初始化为只包含参数指定的单个项。

getItem()

从列表中返回指定的项。

insertItemBefore()

在指定位置将一个新项插入到列表中。

removeItem()

从列表中移除现有项目。

replaceItem()

用新项替换列表中的现有项。

示例

使用 SVGLengthList

可以从 SVGAnimatedLengthList 对象中检索 SVGLengthList 对象,而 SVGAnimatedLengthList 对象本身可以从许多可动画长度属性中检索,例如 SVGTextPositioningElement.x

HTML

html
<svg
  viewBox="0 0 200 100"
  xmlns="http://www.w3.org/2000/svg"
  width="200"
  height="100">
  <text id="text1" x="10" y="50">Hello</text>
</svg>
<button id="equally-distribute">Equally distribute letters</button>
<button id="reset-spacing">Reset spacing</button>
<div>
  <b>Current <code>SVGLengthList</code></b>
  <pre><output id="output"></output></pre>
</div>

JavaScript

js
const text = document.getElementById("text1");
const output = document.getElementById("output");
const list = text.x.baseVal;
function equallyDistribute() {
  list.clear();
  for (let i = 0; i < text.textContent.length; i++) {
    const length = text.ownerSVGElement.createSVGLength();
    length.value = i * 20 + 10;
    list.appendItem(length);
  }
  printList();
}
function resetSpacing() {
  const length = text.ownerSVGElement.createSVGLength();
  length.value = 10;
  list.initialize(length);
  printList();
}
function printList() {
  output.textContent = "";
  for (let i = 0; i < list.length; i++) {
    output.innerText += `${list.getItem(i).value}\n`;
  }
}
printList();

document
  .getElementById("equally-distribute")
  .addEventListener("click", equallyDistribute);
document
  .getElementById("reset-spacing")
  .addEventListener("click", resetSpacing);

结果

规范

规范
Scalable Vector Graphics (SVG) 2
# InterfaceSVGLengthList

浏览器兼容性

另见