SVGTransformList: replaceItem() 方法

Baseline 已廣泛支援

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

SVGTransformList 介面的 replaceItem() 方法用一個新項替換列表中的現有項。

插入的項是項本身,而不是副本。

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

  • 如果該項已經在此列表中,請注意要替換的項的 index 是在移除該項之前的值。

語法

js
replaceItem(newItem, index)

引數

newItem

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

index

一個 integer;新項應替換現有項的索引,為無符號長整型。

返回值

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

異常

此方法可能會丟擲以下型別之一的DOMException

NoModificationAllowedError DOMException

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

IndexSizeError DOMException

如果索引號大於或等於 numberOfItems,則會丟擲此異常。

示例

替換列表中的變換

html
<svg width="200" height="200" id="mySvg">
  <rect width="100" height="100" fill="blue" transform="translate(50,50)" />
</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 rotation transformation
const rotateTransform = svgElement.createSVGTransform();
rotateTransform.setRotate(45, 50, 50);

transformList.replaceItem(rotateTransform, 0);

// Log the details of the new transformation
console.log(`New Transformation Type: ${transformList.getItem(0).type}`); // Output: 4 (e.g. SVG_TRANSFORM_ROTATE)

規範

規範
Scalable Vector Graphics (SVG) 2
# __svg__SVGNameList__replaceItem

瀏覽器相容性

另見