javascript - 在 X 轴刻度上呈现 HTML

标签 javascript html d3.js graph

我想在我的 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>"; })

在图表本身上。

我错过了什么吗?

最佳答案

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

诀窍是使用svg:foreignObject(如@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;
}

关于javascript - 在 X 轴刻度上呈现 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295720/

相关文章:

javascript - 在 IE 中禁用输入文本框的粘贴(Control V)

javascript - 在使用 JavaScript 完成的第二个 onclick() 事件之后,css 中的悬停事件不起作用

javascript - 将字符串转换为图像并将其发送到 WhatsApp

java - Thymeleaf <select> 标签生成选项(数字)

javascript - 如何更改使用 $location 与 angularJS 的 URL

php - Javascript 饼图 php 到 javascript 对象数组

javascript - 在 onclick 事件后显示文本

javascript - 如何循环枚举值以在单选按钮中显示?

jquery - 每个 div 之间的空白不会消失 [CSS]

javascript - D3.js 饼图..选中时饼图切片可以移动吗?