无法更改SVG元素的类名

0as*_*am0 4 html javascript css svg

我想通过单击按钮更改应用于SVG的类.代码在这里.

我的SVG看起来像:

<svg id="test" class="fill" xmlns="http://www.w3.org/2000/svg" width="100%" height="200px" >
      <path id="path22276" d="m500 81c-41-6-110-35-110-46 0-6 32 6 48 19 8 5 53 12 101 14 78 4 93 1 144-22 32-14 60-26 64-26 8 0-37 34-62 47-28 15-131 22-185 14z"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

我尝试了以下代码:

  document.getElementById("test").className = "halffill";
  document.querySelector("svg.fill").setAttribute("class","halffill");
Run Code Online (Sandbox Code Playgroud)

我针对普通的div标签测试了相同的javascript代码.它工作正常.SVG有一些限制吗?请帮我解决这个问题.

Pau*_*eau 16

所述className的SVG元素上属性具有从不同的定义classNameHTML元素的属性.

在HTML中,className是一个字符串.在SVG中它是一个SVGAnimatedString对象.这就是你不能做到的原因svgElement.className = "halffill".

但是,第二行(使用setAttribute())应该有效.


小智 5

问题是 javascript 不会在源代码中更新。您需要检查检查模式中的更改。第一个对我也不起作用,但第二个有效。

document.querySelector("svg.fill").setAttribute("class","halffill");
Run Code Online (Sandbox Code Playgroud)

单击旨在更改类名的按钮,然后进入检查模式并检查svg标签的类名

注意:要进入检查模式,请右键单击屏幕上的任意位置,然后单击“检查”或在 Windows 的 google chrome 中使用 ctrl + shift + I。


小智 5

该版本setAttribute适用于我。对于className,您需要baseVal在SVG中:

document.getElementById("test").className.baseVal = "halffill";
Run Code Online (Sandbox Code Playgroud)


小智 1

问题是 JavaScript加载类型设置为onload在加载主体而不是onclick按钮时调用函数。

解决方案:您可以在 javascript 部分的右上角看到一个齿轮图标。单击它并将加载类型更改为No wrap -in <head>