D3重新绘制再次添加元素

时间:2015-10-19 07:18:17

标签: d3.js dynamic-resizing

我第一次调用drawLegend后的html看起来像这样:

<svg>
   <g class="legend">
       <rect class="active-dimension-rect"></rect>
       <text class="dimension-text">Some text</text>
   </g>
   <g class="legend">
       <rect class="active-dimension-rect"></rect>
       <text class="dimension-text">Some text</text>
   </g>
<svg>

在窗口调整大小时我再次调用该函数,但现在我的html看起来像这样:

<svg>
   <g class="legend">
       <rect class="active-dimension-rect"></rect>
       <text class="dimension-text">Some text</text>
       <rect class="active-dimension-rect"></rect>
       <text class="dimension-text">Some text</text>
   </g>
   <g class="legend">
       <rect class="active-dimension-rect"></rect>
       <text class="dimension-text">Some text</text>
       <rect class="active-dimension-rect"></rect>
       <text class="dimension-text">Some text</text>
   </g>
<svg>

如何在输入时附加rect和text元素?目前我唯一能让它工作的方法是在调整大小时从dom中删除元素(rect和text)。

 d3.select(window).on('resize', drawLegend);

function drawLegend() {
        var legendScale = d3.scale.ordinal()
                            .domain(dimensions)
                            .rangeRoundBands([0, legendWidth], .1);

        var legendGroups = legendSVG.selectAll(".legend").data(dimensions);

        legendGroups.enter().append("g")
                        .attr("class", "legend");

        legendGroups.attr("transform", function (d, i) {
                        return "translate(" + legendScale(d) + ",0)";
                    });


        legendGroups.exit().remove();

        var legendRects = legendGroups.append("rect")
                        .attr("width", 18)
                        .attr("height", 18)
                        .attr('class', 'active-dimension-rect')
                        .attr('id', function(d){
                            return 'dimension-rect-' + d.replace(/\s+/g, '');
                        })
                        .style({"fill": colourScale});

        var legendText = legendGroups.append("text")
                            .attr("dy", "1em")
                            .attr("dx", 20)
                            .attr('dimension', function(d) { return d })
                            .attr('class', 'dimension-text')
                            .attr('rectId', function(d) { return'dimension-rect-' + d.replace(/\s+/g, '') })
                            .style({"text-anchor": "start", 'font-size': '14px'})
                            .text(function(d) {
                                visibleDimensions.push(d);
                                return d;
                            });
}

0 个答案:

没有答案