【发布时间】:2019-02-22 17:11:34
【问题描述】:
我需要使用 SVG/折线元素动态创建迷你图,纯 HTML 的示例完美运行当我使用 JavaScript 创建元素并添加属性时出现问题。
创建元素的功能
function createElement(type, attributes, someElement) {
var element = type == "svg" ? document.createElementNS('http://www.w3.org/2000/svg', 'svg') : document.createElement(type);
for (var key in attributes) {
if (key === "class") {
var cls = attributes[key];
for (var c in cls)
element.classList.add(cls[c]);
} else {
element[key] = attributes[key];
}
}
someElement.appendChild(element);
}
在这里,我创建了 SVG 元素并将其添加到名为 filter_r_inner 的 div 中,然后添加属性。
var newElement = createElement("svg", {
"class": ['mktcap_spark'],
"id": "weekly_svg",
"viewBox": "0 0 500 100"
}, filter_r_inner);
var weekly_svg = document.getElementById("weekly_svg");
weekly_svg.setAttribute("viewBox", "0 0 500 100");
在这里我创建了折线元素并将其添加到 SVG 元素中,然后添加属性。
var newElement = createElement("polyline", {
"id": "weekly_poly"
}, weekly_svg);
var weekly_poly = document.getElementById("weekly_poly");
weekly_poly.setAttribute('points', "00,120 20,60 40,120 60,10 80,80 100,80 120,60 140,100 160,90 180,80 200, 110 220, 10 240, 70 260, 100 280, 100 300, 40 320, 0 340, 100 360, 100 380, 120 400, 60 420, 70 440, 80 460, 20 480, 50 500, 30");
weekly_poly.setAttribute("fill", "none");
weekly_poly.setAttribute("stroke", "#e9be3d");
weekly_poly.setAttribute("stroke-width", "8");
上面没有像我预期的那样渲染 SVG 迷你图,但是添加了所有属性,但没有显示。
我也尝试过以这种方式从this 问题中添加积分,这给了我一个每周_svg.points 未定义的错误
var point = weekly_svg.createSVGPoint();
point.x = 10;
point.y = 20;
weekly_poly.points.appendItem(point);
我也研究了 setAttributeNS,但它需要一个“命名空间”,我试过了,但仍然没有显示。
weekly_poly.setAttributeNS('http://www.w3.org/2000/svg', 'points', "00,120 20,60 40,120 60,10 80,80 100,80 120,60 140,100 160,90 180,80 200, 110 220, 10 240, 70 260, 100 280, 100 300, 40 320, 0 340, 100 360, 100 380, 120 400, 60 420, 70 440, 80 460, 20 480, 50 500, 30");
weekly_poly.setAttributeNS('http://www.w3.org/2000/svg', "fill", "none");
weekly_poly.setAttributeNS('http://www.w3.org/2000/svg', "stroke", "#e9be3d");
weekly_poly.setAttributeNS('http://www.w3.org/2000/svg', "stroke-width", "8");
这里的示例与纯 HTML 完美配合。
<svg viewBox="0 0 500 100" class="mktcap_spark">
<polyline
fill="none"
stroke="#e9be3d"
stroke-width="8"
points="
00,120
20,60
40,120
60,10
80,80
100,80
120,60
140,100
160,90
180,80
200, 110
220, 10
240, 70
260, 100
280, 100
300, 40
320, 0
340, 100
360, 100
380, 120
400, 60
420, 70
440, 80
460, 20
480, 50
500, 30
"
/>
</svg>
它会呈现如下所示的迷你图
CSS
.mktcap_spark {
width: 130px;
height: 50px;
min-width: 130px;
}
【问题讨论】:
-
3 年后我又遇到了同样的问题,我用谷歌搜索它并在谷歌上找到我自己的问题作为口渴...... gg
标签: javascript html svg polyline