【问题标题】:Render HTML on X-Axis Ticks在 X 轴刻度上渲染 HTML
【发布时间】:2016-08-21 14:46:08
【问题描述】:

我想在我的 D3 图表的 x 轴上呈现 HTML。基本上,我希望轴上的每个标签都成为数据中另一列的超链接。

我试过了

x.domain(data.map(function(d) { return "<a href=\"" + d.SiteUrl + "\">" + d.Name + "</a>"; }));

但它根本不起作用。我没有获得超链接,而是获得了实际的文本值:

<a href="http://example.com">Something</a>

我也试过添加

.tickFormat(function(d) { return "<a href=\"" + d.SiteUrl + "\">" + d.Name + "</a>"; })

在 x 轴上,以及将 .attr("x", ...) 更改为

.attr("x", function(d) { return "<a href=\"" + d.SiteUrl + "\">" + x(d.Name) + "</a>"; })

图表本身。

我错过了什么吗?

【问题讨论】:

标签: javascript html d3.js graph


【解决方案1】:

(基于https://groups.google.com/d/msg/d3-js/zoUjrm75iCg/EJg0YhnTw3YJ

诀窍是使用svg:foreignObject(如cmets 中@thatOneGuy 所述),然后您可以将任何HTML 放置在轴标签内。下面html 处的函数通过data[i].name,可以在其中放置任意HTML。

var height = 500;

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .tickSize(0).tickPadding(0).tickFormat(function(d) {return '';});

var tx = -5;
var ty = 2;
var tw = 50;
var th = 10;

chart.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .selectAll("g")
  .append("svg:foreignObject")
  .attr("width",tw)
  .attr("height",th)
  .attr("x", tx)
  .attr("y", ty)
  .append("xhtml:div")
  .attr("class", "my-x-axis-label")
  .html(function(schema) {return schema;});

CSS:

div.my-x-axis-label {
  font: 10px sans-serif;
}

【讨论】:

    猜你喜欢
    • 2016-11-05
    • 2012-12-12
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多