11. JS操作SVG
warning:
这篇文章距离上次修改已过189天,其中的内容可能已经有所变动。
在JavaScript中操作SVG元素,你可以使用DOM API来获取、修改或创建SVG元素。以下是一些基本的操作示例:
- 获取SVG元素:
var svgElement = document.getElementById('svgElementId');
- 创建SVG元素:
var circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', 50);
circle.setAttribute('cy', 50);
circle.setAttribute('r', 20);
document.getElementById('svgContainer').appendChild(circle);
- 修改SVG元素属性:
svgElement.setAttribute('fill', 'red');
- 添加事件监听器:
svgElement.addEventListener('click', function() {
alert('SVG element clicked!');
});
- 删除SVG元素:
svgElement.parentNode.removeChild(svgElement);
确保你的SVG元素位于正确的命名空间('http://www.w3.org/2000/svg'),并使用\`createElementNS\`来创建它们。使用\`setAttribute\`来设置属性,\`addEventListener\`来添加事件监听器,以及DOM Node methods来添加、移除或操作SVG元素。
评论已关闭