Javascript:如何将SVG图像放入数组中
Javascript: How can I put SVG images into an array?
假设我有三个圆圈 - 一个红色,一个黄色和一个绿色。
<svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="red "></circle> </svg>
<svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="yellow"></circle> </svg>
<svg height="100" width"100"=""> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="green"></circle> </svg>
是否可以创建一个包含这 3 个的数组?如果没有,您能否推荐一种可以创建一个包含红色、黄色和绿色三个圆圈的数组的方法?
非常感谢
如果你在数组中需要它们,请先获取它们的父元素。让我们称之为svgParent
然后这样做。
var svgArr = Array.prototype.slice.call(svgParent.querySelectorAll("svg"));
您应该将三个 SVG 元素放在一个正确的数组中。我们使用父元素element.querySelectorAll()
,因为如果存在其他 svg 元素,我们不想收集这三个元素以外的 svg 元素。
<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="red "></circle> </svg>
<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="yellow"></circle> </svg>
<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke = "black" stroke-width = "3" fill="green"></circle> </svg>
JS代码
var svgArray = document.querySelectorAll('svg');
console.log(svgArray[0]); // svgArray[0] is red circle
https://jsfiddle.net/b9mysaew/演示(检查控制台)
可以使用
document.querySelectorAll('svg');
或document.getElementsByTagName('svg')
将所有svg
元素放在类似对象的数组中。
document.querySelectorAll()
将返回一个NodeList
document.getElementsByTagName('')
会返回HTMLCollection
1- 创建父 SVG 元素
2-将数据绑定到svg并回车()
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom + 20);
var circles = svg.selectAll(".month")
.data(eachcircle);
//loop from 0 to eachcircle.length
circlesdata(eachcircle).append("circle")
.attr("cx", function(d,i) { return d[["x"];})
.attr("cy", function(d,i) { return d["y"];})
.attr("r", function (d) { return d["r"]; })
.style("fill", function(d) { return d["color"]; });
相关文章:
- 使用图像数组列表的simplegallary.js显示适合桌面屏幕的图像
- 在字符串中查找所有图像 src URL 并存储在数组中
- 在ListView中添加JSON数组中存储的图像-ReactNative
- JavaScript中的数组图像循环
- 循环以检查数组中的最后一个图像
- 如何从 URL 数组向文档添加图像列表
- 数组上的多图像上传-Javascript/Jquery
- Jquery/Javascript:通过按下按钮显示数组中的随机图像
- JavaScript:是否可以将图像/信息附加到数组项
- Javascript图像数组预加载速度和从内存中删除
- 将图像数组访问到动态表中
- Javascript检查图像是否在数组中
- Javascript图像数组
- 正在从字节数组加载图像内容
- Javascript:如何将SVG图像放入数组中
- JavaScript 在删除预上传图像时不清除图像数组
- 比较数组图像&值如果ok提交表单
- 画布图案饼图与数组图像
- Javascript数组(图像滑块)(Webkit中的bug ?)
- 在画布中绘制数组图像