扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

setAttribute在SVG中的使用技巧

扬州沐宇科技
2024-06-27 00:43:43
setattribute

在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是一种非常实用的方法。

扫码添加客服微信