温馨提示×

setAttribute在SVG中的使用技巧

小樊
84
2024-06-27 00:43:43
栏目: 编程语言

在SVG中,可以使用setAttribute来动态添加、修改或删除元素的属性。其基本语法如下:

<svg id="mySvg">
  <circle cx="50" cy="50" r="30" fill="red"/>
</svg>

<script>
  var circle = document.getElementById('mySvg').querySelector('circle');
  
  // 添加属性
  circle.setAttribute('stroke', 'black');
  
  // 修改属性
  circle.setAttribute('r', '40');
  
  // 删除属性
  circle.removeAttribute('fill');
</script>

通过上面的例子可以看到,通过setAttribute方法可以很方便地对SVG元素的属性进行操作。当需要对SVG图形进行交互式操作或动态变化时,setAttribute是一种非常实用的方法。

0