Javascript:如何将SVG图像放入数组中?

时间:2016-04-27 09:30:35

标签: javascript arrays 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>

是否可以创建一个包含这3个的数组? 如果没有,你能推荐一种方法,我可以创建一个包含三个红色,黄色和绿色圆圈的阵列吗?

非常感谢

4 个答案:

答案 0 :(得分:0)

<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/为你演示(检查控制台)

答案 1 :(得分:0)

document.querySelectorAll('svg');document.getElementsByTagName('svg')可用于将所有svg元素放入像对象一样的数组中。

document.querySelectorAll()将返回NodeList

document.getElementsByTagName('')将返回HTMLCollection

答案 2 :(得分:0)

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"]; });

答案 3 :(得分:0)

如果你需要在数组中首先获取它们的父元素。我们称之为svgParent然后这样做。

var svgArr = Array.prototype.slice.call(svgParent.querySelectorAll("svg"));

你应该在适当的数组中获得三个svg元素。我们正在使用来自父级的element.querySelectorAll(),因为如果存在其他svg元素,我们不希望收集除这三个之外的svg元素。

相关问题