我正在尝试向我用 JavaScript 创建的 SVGRect 元素添加一个类。我可以看到类已添加到元素(在开发人员工具中),但元素没有相应的样式。如果我将一个类添加到以内联方式创建的 Rect,则该元素会被设置样式。
- SVG 元素有 Rect0
- 我使用“drawSomething”将 Rect1 添加到 SVG 元素
- 我使用“updateSomething”将类“task0”和“task1”添加到 Rect0 和 Rect1。
Rect0 有样式,Rect1 没有。
更新后需要“申请”吗?两个 Rect 元素的宽度在执行“updateSomething”后更新,这让我认为我不需要“应用”。
“rect”规则也不适用于动态创建的 Rect。
此外,我还应该提到我的 SVG 元素是 Angular 组件的一部分。想知道这是否改变了什么。
function drawSomething()
{
let SVG_NS = "http://www.w3.org/2000/svg";
let svg = document.getElementById('editorSvg');
let rect = document.createElementNS(SVG_NS, "rect");
rect.setAttribute("id", "svg-rect-1");
rect.setAttribute("x", "100");
rect.setAttribute("y", "80");
rect.setAttribute("width", "50");
rect.setAttribute("height", "50");
svg.appendChild(rect);
}
function updateSomething()
{
let rect0 = document.getElementById("svg-rect-0");
rect0.style.width = "100";
rect0.setAttribute("class", "task0");
let rect1 = document.getElementById("svg-rect-1");
rect1.style.width = "100";
rect1.setAttribute("class", "task1");
}
drawSomething();
updateSomething();
rect {
stroke: red;
stroke-width: 2;
}
.task0 {
fill: green;
stroke-width: 5;
}
.task1 {
fill: orange;
stroke-width: 5;
}
<div id="svgContainer" class="svgContainer">
<svg id='editorSvg' class='editorSvg' xmlns="http://www.w3.org/2000/svg">
<rect id="svg-rect-0" x="10" y="10" width="50" height="50" class="task" ></rect>
</svg>
</div>
最佳答案
代码似乎工作正常。至少在 Chrome 中。
请注意,通过 CSS 属性 (style.width="100"
) 设置 width
是 SVG 2 的东西,目前还不能在所有浏览器中使用。例如,目前它可以在 Chrome 中使用,但不能在 Firefox 中使用。
另一个问题是,在 CSS 中,属性应该有单位。所以技术上你应该写 rect0.style.width = "100px";
(注意 px
)
无论如何,为了更好地跨浏览器工作,我建议使用:
rect0.setAttribute("width", "100");
不过,您设置 class
的方式看起来不错。除了宽度之外,我看不出有任何其他原因应该被破坏。
更新
啊,我明白你现在想做什么了。
你可以这样做:
import { Component, Renderer2 } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(private renderer: Renderer2) {
}
public addRect1 = () => {
let svg = document.getElementById('editorSvg');
const rect = this.renderer.createElement("rect", 'svg');
this.renderer.setAttribute(rect, "id", "svg-rect-1");
this.renderer.setAttribute(rect, "x", "100");
this.renderer.setAttribute(rect, "y", "80");
this.renderer.setAttribute(rect, "width", "50");
this.renderer.setAttribute(rect, "height", "50");
this.renderer.appendChild(svg, rect)
}
styleRect0 = () => {
let rect = document.getElementById("svg-rect-0"); // as unknown as SVGRectElement;
rect.style.width = "100";
rect.classList.add("task0");
}
styleRect1 = () => {
let rect = document.getElementById("svg-rect-1"); // as unknown as SVGRectElement;
rect.style.width = "100";
rect.classList.add("task1");
}
}
关于html - 如何将类添加到使用 JavaScript 动态创建的 SVGRect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56469543/