【发布时间】:2019-06-08 01:48:28
【问题描述】:
我正在尝试向使用 JavaScript 创建的 SVGRect 元素添加一个类。我可以看到该类已添加到元素中(在开发人员工具中),但该元素没有相应地设置样式。如果我将一个类添加到内联创建的 Rect 元素的样式。
- SVG 元素具有 Rect0
- 我使用“drawSomething”将 Rect1 添加到 SVG 元素中
- 我使用“updateSomething”将类“task0”和“task1”添加到 Rect0 和 Rect1。
Rect0 有样式,Rect1 没有。
更新后是否需要“申请”?执行“updateSomething”后,两个 Rect 元素的宽度都会更新,这让我认为我不需要“应用”。
“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>
【问题讨论】: