SVGTransformList: insertItemBefore() 方法

Baseline 已廣泛支援

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

SVGTransformList 介面的 insertItemBefore() 方法會在指定位置將新項插入到列表中。

第一個項的索引為 0。插入的項是該項本身,而不是副本。

  • 如果 newItem 已經存在於某個列表中,在將其插入到此列表之前,會先將其從之前的列表中移除。

  • 如果該項已在此列表中,請注意,要插入到其之前的項的 index 在該項被移除之前就已經確定了。

  • 如果 index 等於 0,則新項將插入到列表的開頭。

  • 如果 index 大於或等於 numberOfItems,則新項將被新增到列表的末尾。

語法

js
insertItemBefore(newItem, index)

引數

newItem

要插入到列表中的一個 SVGTransform 項。

index

一個 integer;新項應插入的位置,作為一個無符號長整型。

返回值

一個 SVGTransform 物件;從列表中插入的項。

異常

NoModificationAllowedError DOMException

如果 SVGTransformList 對應於只讀屬性,或者物件本身是隻讀的,則會丟擲此異常。

示例

在列表中插入變換

html
<svg width="200" height="200" id="mySvg">
  <rect width="100" height="100" fill="blue" />
</svg>
js
const svgElement = document.querySelector("svg");
const rectElement = svgElement.querySelector("rect");

// Access the transform list of the <rect> element
const transformList = rectElement.transform.baseVal;

// Create a new translate transformation
const translateTransform = svgElement.createSVGTransform();
translateTransform.setTranslate(50, 50);

// Insert the translation transformation at the beginning of the list
transformList.insertItemBefore(translateTransform, 0);

// The transformation list length and type
console.log(`Number of transformations: ${transformList.length}`); // Output: 1
console.log(`Transformation Type: ${transformList.getItem(0).type}`); // Output: 2 (e.g. SVG_TRANSFORM_TRANSLATE)

規範

規範
Scalable Vector Graphics (SVG) 2
# __svg__SVGNameList__insertItemBefore

瀏覽器相容性

另見