我想在 D3 生成的 SVG 文本中将长句子分成两行。但我不能在D3/javascript
中做到这一点.我试过 \n
和 <br/>
, 但它们不工作。
<!DOCTYPE html>
<html>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript">
var margin = {top: 80,left: 70, bottom: 80,right: 100},
height = 660 - margin.top - margin.bottom,
width = 1320 - margin.left - margin.right;
var chart = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate("+margin.left+","+margin.top+")");
chart.append('text')
.attr('x', 100)
.attr('y', 100)
.text("I want to have this \n sentence in two lines")
.attr("dy", "1em")
.style("text-anchor", "middle")
.style("font-family", "Helvetica, Arial, sans-serif")
.style("font-weight", "bold")
.style("font-size", "16px" )
.style("fill", "#1ABC9C");
</script>
</body>
</html>
最佳答案
使用 .append("foreignObject").append("xhtml:span").html("your text <br> will goes here");
而不是 .text()
功能。
例子:
var mytext=svg.append("foreignObject").attr("width"100).attr("height",50).append("xhtml:span")
.html("Your Text <br> goes here");
此处不需要 br 标签,当达到指定宽度时,文本将自动换行到下一行。
关于javascript - 无法在 D3 生成的 SVG 文本中打断长句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20867514/