我为D3制作的地图创建了许多SVG文本元素。 它们在我的文档中显示为Body的孙子,以及我创建的SVG容器的子项。
见这里:my DOM
然而,每个元素都堆在另一个元素的顶部,卡在0,0位置。 有趣的是,当文本元素位于正文的外部时,它们会呈现正常。
以下是我使用D3生成元素的方法......
var a=["", "Albany Park", "Archer Heights", "Armour Square", "Ashburn", "Auburn Gresham", "Austin", "Avalon Park", "Avondale", "Belmont Cragin", "Beverly", "Bridgeport", "Brighton Park", "Burnside", "Calumet Heights", "Chatham", "Chicago Lawn", "Clearing", "Douglas", "Dunning", "East Garfield Park", "East Side", "Edgewater", "Edison Park", "Englewood", "Forest Glen", "Fuller Park", "Gage Park"];
var canvas = d3.select("body") //select the body
.append("svg") //append an svg container
.attr("id", "drawingBoard") //give that container an id
.attr("height", 600) //specify dimensions
.attr("width", 600)
canvas.selectAll("#drawingBoard")
.data(a)
.enter() //make as many potential elements as there are data items
.append("text") //make those potential elements real
.style("font-family", "Calibri", "sans-serif")
.style("font-size", ".6em")
.html(function(x){return x+ "<br>"}); //Populates the new elements with text.
<html>
<head>
<meta charset="utf-8">
<title>En Route to D3, SVG, and Javascript Mastery</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
</body>
</html>
答案 0 :(得分:0)
svg中的文本节点不会将自己定位为普通的HTML DOM元素。相反,他们通过x
和y
属性(或转换)require explicit positioning。通过不设置这些属性,浏览器会将它们设置为默认值0
。
那么,我们如何定位它们呢?这就是d3
数据绑定魔法派上用场了。在这里,我使用attr方法,它接受函数回调作为它的第二个参数。向此函数传递数据(您的文本)和数据数组中元素的索引。所以它就这么简单:
index * 15 -> 0, 15, 30, 45, etc...
这是一个像素位置。下面我也加了10,所以数组中的第一个值没有减半。
var a=["Albany Park", "Archer Heights", "Armour Square", "Ashburn", "Auburn Gresham", "Austin", "Avalon Park", "Avondale", "Belmont Cragin", "Beverly", "Bridgeport", "Brighton Park", "Burnside", "Calumet Heights", "Chatham", "Chicago Lawn", "Clearing", "Douglas", "Dunning", "East Garfield Park", "East Side", "Edgewater", "Edison Park", "Englewood", "Forest Glen", "Fuller Park", "Gage Park"];
var canvas = d3.select("body") //select the body
.append("svg") //append an svg container
.attr("id", "drawingBoard") //give that container an id
.attr("height", 600) //specify dimensions
.attr("width", 600);
var g = canvas.append("g")
.attr("transform", "translate(50,50)");
g.selectAll('text').data(a)
.enter() //make as many potential elements as there are data items
.append("text") //make those potential elements real
.style("font-family", "Calibri", "sans-serif")
.style("font-size", ".6em")
.text(function(x){return x}) //<-- use .text, .html is meaningless here since it's not html. Also, no need for the <br>, it's svg so you'll just get that as text
.attr('y', function(d,i){
// set the x attribute
return (i * 15);
})
.style('alignment-baseline', 'hanging');
&#13;
<html>
<head>
<meta charset="utf-8">
<title>En Route to D3, SVG, and Javascript Mastery</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
</body>
</html>
&#13;