javascript - 在 SVG 中操作 <path> 的类

标签 javascript svg

我在 SVG 中有一个 JavaScript(纯、简单的 JS,没有 jQuery),我在其中获取了 <path>通过 document.getElementById()。现在我尝试向其中添加一个“active”类,但我被卡住了。

这是到目前为止我的(简化的)代码:

var element = document.getElementById(myId);
//A console.log(element) returns the <path>-Object, so I guess this is working.

if (element) {
    //Add a class
}

我可以获得 -Object 的当前类:

console.log(element.className.baseVal);

但我无法为此添加“事件”...我已经尝试了几种方法,例如

element.attr('class', className + ' active');

.. 返回

Uncaught TypeError: Object #<SVGPathElement> has no method 'attr'

有没有一种简单的方法可以在空白 JavaScript 中做到这一点?我在这里遗漏了什么吗?

最佳答案

这样做:

element.setAttribute('class', className + ' active');

你试图用 jquery 的语法来做到这一点

关于javascript - 在 SVG 中操作 <path> 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22912991/

相关文章:

javascript - function(a, b) 的值是多少?

html - 如何在 html <polygon> 或 <path> 之外填充?

css - 使用媒体查询时保持 SVG 居中

jquery - 部分填充 SVG 背景

svg - Imagemagick SVG 到 PDF 转换图像质量很差

html - 更改svg中图像的背景颜色

javascript - 如何在 Node.js 中请求图像和输出图像

Javascript 嵌套对象访问根级别

javascript - Node 看不到模块

javascript - promise -如何处理已知错误