我是d3.js的新手,我要求在矩形的右上角创建一个关闭按钮[x]。点击按钮后,应从图表中删除矩形 我正在考虑使用链接内容中建议的svg remove 我目前使用字母X作为关闭按钮。然而,这个实现似乎不起作用,字母不可见(尽管出现在DOM上)。
bl.ocks链接到这里:http://bl.ocks.org/bhandarisumit/b48e134e358f94a290a2
代码:
var margin = {top: 15, right: 40, bottom: 20, left: 50},
width = 960 - margin.left - margin.right,
height = 240 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("id", "clip-rect")
.attr("x", "0")
.attr("y", "0")
.attr("width", width)
.attr("height", height);
var chartBody = svg.append("g")
.attr("clip-path", "url(#clip)");
var rect = chartBody.append('svg:rect')
.attr('width', width-20)
.attr('height', height-20)
.attr('fill', 'white');
var labeledRect = chartBody.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("height", height-20)
.attr("width", width-20)
.style("stroke", "red")
.attr("class", "labelbox")
.style("fill", "none");
var closeArea = chartBody.append('text')
.text('X')
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
labeledRect.append('text').attr('color','black').text('X');

body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
rect {
fill: #fff;
}

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.js"></script>
&#13;
答案 0 :(得分:1)
字母&#39; X&#39;被放置在&#39; rect&#39;区域之外。元素,因此不可见。
&#39;文字&#39;元素有&#39; x&#39;并且&#39; y&#39;其位置的属性(默认为0),
但是坐标表示文本左下角的位置
所以,如果你没有设置&#39; y&#39;属性,文字不可见,因为&#39; y&#39;是0.
我在代码中插入了一行.attr("y", 20)
。请试试这个。
var closeArea = chartBody.append('text')
.text('X')
.attr("y", 20)
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
替代解决方案是使用dominant-baseline
属性,如下所示:
var closeArea = chartBody.append('text')
.text('X')
.attr("dominant-baseline","text-before-edge")
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");