How can I select :last-child in d3.js?

后端 未结 6 2152
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 08:55

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

I am trying to select them, one at t

6条回答
  •  星月不相逢
    2020-12-31 09:50

    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.

提交回复
热议问题