如何在d3.js中选择:last-child? [英] How can I select :last-child in d3.js?

查看:160
本文介绍了如何在d3.js中选择:last-child?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要操纵轴的第一个和最后一个刻度的text元素,以使它们更靠近中心.

I need to manipulate the text elements of the first and last tick of an axis to bring them more towards the center.

我试图一次选择它们,例如svg.select('.tick:last-child text'),但是它不起作用.然后,我将应用.transform('translate(4,0)') ...

I am trying to select them, one at the time, with something like svg.select('.tick:last-child text') but it doesn't work. I'd then apply .transform('translate(4,0)')...

我做错什么了吗?我该如何实现?

Am I doing something wrong? How can I achieve this?

推荐答案

您可以做的一件事是通过向d3.selection.prototype添加方法来创建自定义子选择.您可以创建一个selection.first()方法来选择一个选择中的第一个项目,并创建一个selection.last()方法来选择一个最后一个项目.例如:

One thing you could do is to create custom sub-selections by adding methods to d3.selection.prototype. You could create a selection.first() method that selects the first item in a selection, and a selection.last() method that selects the last item. For instance:

d3.selection.prototype.first = function() {
  return d3.select(this[0][0]);
};
d3.selection.prototype.last = function() {
  var last = this.size() - 1;
  return d3.select(this[0][last]);
};

这将使您执行以下操作:

This would let you do the following:

var tickLabels = svg.selectAll('.tick text');

tickLabels.first()
  .attr('transform','translate(4,0)');
tickLabels.last()
  .attr('transform','translate(-4,0)');


当然,如果要这样做,则需要确保只有一个轴.否则,请在初始选择中指定轴:


Of course, you need to make sure that you only have one axis if you do it that way. Otherwise, specify the axis in your initial selection:

var tickLabels = svg.selectAll('.axis.x .tick text');

此处 是一个示例.

HERE is an example.

这篇关于如何在d3.js中选择:last-child?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆