2016-03-31 7 views
2

完全なd3初心者ここにあります。私はこのd3ツリーを使用しています(ここでは作業中のhttps://jsfiddle.net/Joe123/vq4jpr1s/16/です)、各ノードのテキストがノードのサイズに折り返されるようにします。しかし、同じノード上で複数回クリックすると、テキストが折り返されて元に戻ってしまい、その理由がわかりません。誰にもアイデアはありますか?どんな助けでも大歓迎です。ここでテキストはd3ツリーノードにラップされません

ラップ機能である:

function wrap(text, width) { 
    text.each(function() { 
    var text = d3.select(this), 
     words = text.text().split(/\s+/).reverse(), 
     word, 
     line = [], 
     lineNumber = 0, 
     lineHeight = 1.1, 
     y = text.attr("y"), 
     dy = parseFloat(text.attr("dy")), 
     tspan = text.text(null).append("tspan").attr("x", 5).attr("y", y).attr("dy", dy + "em"); 
    while (word = words.pop()) { 
     line.push(word); 
     tspan.text(line.join(" ")); 
     if (tspan.node().getComputedTextLength() > width) { 
     line.pop(); 
     tspan.text(line.join(" ")); 
     line = [word]; 
     tspan = text.append("tspan").attr("x", 5).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); 
     } 
    } 
    d3.select(this.parentNode.children[0]).attr("height", 20 * (lineNumber+1)); 


    }); 
} 

wrap(d3.selectAll('text'),150); 

以下は、クリック機能である、私はここからラップ機能が、運を呼び出してみました。

function click(d) { 

    if (d.children) { 
    d._children = d.children; 
    d.children = null; 

    } else { 
    d.children = d._children; 

    } 
    update(d); 
} 

答えて

3

問題は、ホワイトスペースに基づいて分割しようとすると、テキストにすでにスペースがないことです(2回目のオンワード)。

ので、代わりの

words = text.text().split(/\s+/).reverse(), 

をやってこのよう

words = d3.select(this).data()[0].name.split(/\s+/).reverse(), 

実施例here

+1

完璧!それは完璧に働いた!どうもありがとうございます! – user2891996

0

タイムマシンを発明しましたか?

1

それを行う問題は、同じテキストで何度も何度もwrapを使用していることです。これは私がやったことです:

まず、私はnewTextへの新しいテキストのクラス変更:

nodeEnter.append("text") 
    .attr("x", function(d) { 
     return d._children ? -0 : 8; 
    }) 
    .attr("y", 3) 
    .attr("dy", "0em") 
    .attr("text-anchor", "middle") 
    .attr("class", "newText") 
    .text(function(d) { 
     return d.name; 
    }) 

    wrap(d3.selectAll('.newText'),150); 

をそして、機能のクリックで、私はすべてのテキストのクラスを変更:

function click(d) { 

    if (d.children) { 
    d._children = d.children; 
    d.children = null; 

    } else { 
    d.children = d._children; 

    } 
    d3.selectAll("text").attr("class", "text"); 
    update(d); 
} 
+0

これを見ている人は誰でも、私はそれを試して、それも働いた。 – user2891996

関連する問題