Element.setAttributeNS
时间: 2024-06-09 10:06:41 浏览: 6
Element.setAttributeNS() 是一个 JavaScript 方法,用于设置元素节点的指定命名空间下指定名称的属性值。它和 Element.setAttribute() 方法类似,但可以明确指定属性的命名空间。命名空间是指一个字符串类型的标识符,用于区分不同的 XML 元素和属性。
方法语法如下:
```javascript
element.setAttributeNS(namespaceURI, qualifiedName, value);
```
参数说明:
- namespaceURI:必需。指定属性的命名空间 URI。
- qualifiedName:必需。指定属性的限定名称,包括前缀和本地名称。
- value:必需。指定属性的值。
示例代码:
```html
<svg width="100" height="100">
<rect id="rect1" x="10" y="10" width="20" height="20" fill="red" />
</svg>
<script>
let rect = document.getElementById("rect1");
rect.setAttributeNS(null, "fill", "blue"); // 设置 fill 属性为蓝色,命名空间为 null
rect.setAttributeNS("http://www.w3.org/2000/svg", "width", "30"); // 设置 width 属性为 30,命名空间为 SVG
</script>
```
在上面的示例中,我们首先通过 getElementById() 方法获取 ID 为 "rect1" 的矩形元素,然后使用 setAttributeNS() 方法设置该元素的 fill 属性为蓝色,命名空间为 null,即默认命名空间。接着,我们使用 setAttributeNS() 方法设置该元素的 width 属性为 30,命名空间为 SVG。注意,SVG 命名空间的 URI 是 "http://www.w3.org/2000/svg"。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)