【问题标题】:Create a close button on a svg using d3.js使用 d3.js 在 svg 上创建关闭按钮
【发布时间】:2015-02-15 13:41:42
【问题描述】:

我是 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>

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:

    字母'X'被放置在'rect'元素的区域之外,所以它是不可见的。
    'text' 元素的位置具有 'x' 和 'y' 属性(默认为 0),
    但坐标表示文本左下角的位置。
    所以如果你不设置'y'属性,文本是不可见的,因为'y'是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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-24
      相关资源
      最近更新 更多